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
CodePudding user response:
Yes, the ternary shorthand (elvis) operator can be chained with itself in PHP.
print(false ?: false ?: "expected"); //expected
print("\n");
print(false ?: "expected" ?: false); //expected
print("\n");
print("expected" ?: false ?: false); //expected
print("\n");
print(false ?: "expected" ?: "wrong"); //expected
OnlinePHP sandbox: https://onlinephp.io/c/7ced9
CodePudding user response:
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:
$a = 1;
$b = 2;
$c = 3;
$result = $a ?: $b ?: $c;
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.