Ternary Operator¶

Definition¶
The expression
(expr1) ? (expr2) : (expr3)
evaluates to expr2 if expr1 does not evaluate to FALSE, and expr3 if expr1 evaluates to FALSE. Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expressionexpr1 ?: expr3
(short-hand ternary) returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise. • php.net
Aliases¶
- (expr1) ? (expr2) : (expr3) : conditional operator, inline if (iif), or ternary if
- expr1 ?: expr3 : Elvis operator
Usage¶
It is a shorter form of if-then-else, easily written in one line.
Examples¶
$result = $is_singular ? 'word' : 'words'; // normal ternary operator
$title = $specified_title ?: $default_title ; // shorthand ternary operator
// which is equivalent to
$title = $specified_title != false ? $specified_title : $default_title
References¶
Related articles¶
- Null Coalescing operator operator ifthen conditional