PHP – 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:

&lt;?<a title="See also PHP - Checking Exceptions speed" href="http://www.whileifblog.com/2012/05/12/php-checking-exceptions-speed/">php</a>

	$host = strlen($host) &gt; 0 ? $host : htmlentities($host);

?&gt;

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.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

More in Code, PHP, Tips (129 of 192 articles)


A small tip this one but you can save a few characters by using shorthand for the $(document).ready function. Instead ...