The ternary shorthand (elvis) operator checks if the first value is truthy. If it is, PHP evaluates the expression to that first value. If not, the result is the second value.
$falseyValue ?: 'expected'; //expected
But I’ve been using the null coalescing operator, and in some cases it is useful to chain it like so:
$nullValue ?? $anotherNullValue ?? 'expected'; //expected
That checks if $nullValue
exists and is not null. If not, check if $anotherNullValue
exists and is not null. If not, evaluate to ‘expected’.
Can the ternary shorthand operator be used in that manner?
$falseyValue ?: $anotherFalseyValue ?: 'expected'; //expected
2
Answers
Yes, the ternary shorthand (elvis) operator can be chained with itself in PHP.
OnlinePHP sandbox: https://onlinephp.io/c/7ced9
Yes, you can chain multiple ternary shorthand operators in PHP. The shorthand ternary operator is a shorthand way of writing a ternary expression. It’s written as expr1 ?: expr3 which is equivalent to expr1 ? expr1 : expr3.
Here’s an example of chaining multiple ternary shorthand operators:
In this example, if $a is truthy, $result will be set to $a, otherwise, it will check $b, if $b is truthy, $result will be set to $b, otherwise, $result will be set to $c.