Use Ternary Operators

The benefit of the ternary operator is debatable (there’s only one, by the way). Here is a line of code from an audit we performed recently:

    $host = strlen($host) > 0 ? $host : htmlentities($host);

Oops! The author actually means to escape $host if the string length is greater than zero, but instead accidentally does the opposite. Easy mistake to make? Maybe. Easy to miss during a code audit? Certainly. Concision doesn’t necessarily make the code any better.

The ternary operator may be fine for one-liners, prototypes, and templates, but we strongly believe that an ordinary conditional statement is almost always better. PHP is descriptive and verbose. We think code should be, too.

This entry was posted on Wednesday, February 16th, 2011 at 2:35 am and is filed under Tips. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

6 Responses to “Use Ternary Operators”

Travis Black

May 19, 2011 at 7:16 pm

I think ternary is great in templates.

<div id="post" class="isFlagged) ? ‘flagged’ : ‘unflagged’; ?>”>
getBody(); ?>

Travis Black

May 19, 2011 at 7:17 pm

lol… your replies don’t allow php tags… which makes it hard to discuss php code…


May 19, 2011 at 7:52 pm

You can now post code in comments by wrapping code in [ code ] [/ code ] minus the spacing of course.

$foo = "Code in Comment";
echo $foo;
Owen Byrne

May 19, 2011 at 8:07 pm

I’m not sure why you wouldn’t just do:

$host = htmlentities($host);

May 19, 2011 at 9:49 pm

The ternary operator is like a gun – if you don’t know how it works, you shouldn’t use it. The example you gave doesn’t strike me as confusing in the least, but I do agree that it would be clearer with something like

if(!empty($host)) $host = htmlentities($host);

That said, I do like to use the ternary for dealing with default values, e.g.:

$host = isset($row['host']) ? $row['host'] : 'localhost';

and I really like the ability to leave out the middle condition since 5.3, much like the “or equal” ruby operator.


June 1, 2011 at 4:24 pm

Personally I use them when ever possible, like most tools of the trade it has its uses, but can be abused.

Leave a Reply