Thursday, April 19, 2012

PHP Ternary Operator

Ever want a short way to quickly evaluate a conditional and set a variable based on it's result? You could do it the long way and do something like:

if ( $var == 1 ) $moo = 2; else $moo = 3;

Or you could use a ternary operator, for example

$moo = ( $var == 1 ? 2 : 3 );

It evaluates the conditional before the question mark, if it's true it gives you the first item before the colon, otherwise it gives you the item after the colon. This is useful for many situations such as showing a quick representation of a boolean:

echo ( $var ? 'Yes' : 'No' );

It makes booleans more digestible to those users who may not know that a 1 is "Yes", in situations like pulling a boolean value from a table and displaying it to an admin.

No comments:

Post a Comment