What is ternary operator in PHP?

Filed under: PHP Examples; Author: phpman; Posted: January 30, 2007 at 9:19 am;

Ternary Operator

In computer science a ternary operator is an operator that takes three arguments. The arguments and result can be of different types.

Example: conditional operator is the “?:” (or ternary) operator.

PHP Code example for ternary operator: assigning a default value

//PHP COde Example usage for: Ternary Operator
$todo = (empty($_POST[’todo’])) ? ‘default’ : $_POST[’todo’];

// The above is identical to this if/else statement
if (empty($_POST[’todo’])) {
$action = ‘default’;
} else {
$action = $_POST[’todo’];
}
?>
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE , and expr3 if expr1 evaluates to FALSE .

Note: Please note that the ternary operator doesn’t evaluate to a variable, but to the result of a statement. A ternary operator is a statement! If you want to return a variable by reference this is important to know. The statement return $var == 37 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

Important note: Is is recommended that you avoid “stacking” ternary expressions. PHP’s behaviour when using more than one ternary operator within a single statement is non-obvious:

Example 15-4. Non-obvious Ternary Behaviour

// on first glance, the following appears to output ‘true’
echo (true?’true’:false?’t':’f');

// however, the actual output of the above is ‘t’
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? ‘true’ : ‘false’) ? ‘t’ : ‘f’);

// here, you can see that the first expression is evaluated to ‘true’, which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>