PHP Ternary (?) Operator

The ? or ternary operator is similar to the if statement but returns a value derived from one of two expressions separated by a colon. This construct will provide you with three parts of the whole, hence the name "ternary." Which expression is used to generate the value returned depends on the result of a test expression.

Ternary Operator Syntax :

<?php
( expression )?returned_if_expression_is_true:returned_if_expression_is_false;
( expression )?returned_if_expression_is_true:returned_if_expression_is_false;
?>

If the test expression evaluates to true, the result of the second expression is returned; otherwise, the value of the third expression is returned.

Example :


<?php
$mood = "sad";
$text = ($mood=="happy") ? "I'm in a good mood" : "Not happy but $mood";
print "$text";
?>

Output :

Not happy but sad.

In the above example $mood variable is set to "sad" and next line $mood is tested for equivalence to the string "happy". Because this test returns false, the result of the third of the three expressions is returned. The ternary operator can be difficult to read but is useful if you are dealing with only two alternatives and like to write compact code.





Content