PHP Ternary Operator – Shortcut to IF ELSE

by Carey on November 28, 2010

Post image for PHP Ternary Operator – Shortcut to IF ELSE
  • Share
  • CevherShare
  • Share

I consider this chunk to be one you should use with caution.

Above all else, write your code with readability in mind. Don’t get caught in the mentality of “less lines, better code”, as this will ensure any future changes give you or someone else major headaches.

That said, if you have a simple IF ELSE statement then it is possible to use the Ternary Operator syntax to shorten this down to 1 line. Consider the following:

if ($varA == $varB)
{
$valid = 'valid';
}

else

{
$valid = 'invalid';
}

Now this is no doubt fairly common in your applications – a simple comparison determining the value of a variable. This can feasibly be rewritten for one line and still be easily understandable:

$valid =  ($varA == $varB ? 'valid' : 'invalid');

Even someone who does not know about the Ternary Operator would be able to understand this without too much trouble, and will hopefully appreciate the simplicity of the statement. If you were to abuse the Ternary Operator by using it in complex or nested situations, you may well frustrate yourself and others who have to decipher its meaning.

So in conclusion, use the Ternary Operator only for simple comparisons.

{ 2 comments… read them below or add one }

Roger Feese January 22, 2009 at 9:04 pm

You are correct in spirit but I think this is a poor example. Simplifying the boolean comparisons, the above code would be re-factored as:

$valid = ($varA == $varB)

Right??

Maybe you could craft a better example by using non-boolean outcome operands. Something like this perhaps:

$validity = ($varA == $varB) ? ‘valid’ : ‘invalid’

Reply

Carey December 3, 2010 at 11:58 pm

Great point Roger and actually a good way to shorten boolean based operands even further.

Reply

Leave a Comment

Previous post:

Next post: