PHP Reference ยท Operators
PHP ternary and Elvis operators
Reference for the PHP ternary operator ? : and the short Elvis form ?:, with PHP 8 rules for nesting, precedence and how they differ from ??.
The ternary operator condition ? a : b is an expression that gives a when the condition is truthy and b otherwise. The short form a ?: b, nicknamed the Elvis operator, returns a when it is truthy and b if it is not, evaluating a only once.
Use it for small, simple choices. Anything longer reads better as if/else or match.
$label = $count === 1 ? "item" : "items"; $name = $input ?: "anonymous";
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Without the parentheses, PHP 8 refuses to compile the code (read-only, it would stop the script):
echo 1 ? "a" : 2 ? "b" : "c"; // Fatal error: Unparenthesized `a ? b : c ? d : e` is not supported
Syntax
$condition ? $ifTrue : $ifFalse $value ?: $fallback
| Form | Result |
|---|---|
c ? a : b |
a if c is truthy, otherwise b. Only the chosen branch is evaluated. |
a ?: b |
a if a is truthy, otherwise b. a is evaluated once. |
Usage notes
- Nesting needs parentheses. Since PHP 8.0 an unparenthesized chain such as
a ? b : c ? d : eis a compile error (it was deprecated in 7.4). Mixing?:chains is allowed:a ?: b ?: cpicks the first truthy value. - Truthiness, not null.
?:replaces0,"","0",[]andfalseas well asnull. For only-null defaults use??. ?:warns on undefined variables,??does not.- Not a statement. Do not use it for side effects like
$ok ? save() : abort();. Useif. - Precedence. The ternary binds weaker than
.,+and comparison but stronger than assignment:echo "x" . $a ? "y" : "z"tests the concatenated string. Parenthesize each side. - Readability. One level of ternary is fine. For three or more outcomes use
match. - Return and arguments. It works anywhere an expression is allowed, including
return, arguments and string building with parentheses.