Why is this printing 2
?
echo true ? 1 : true ? 2 : 3;
With my understanding, it should print 1
.
Why is it not working as expected?
The JavaScript ternary operator also works to do multiple operations in one statement. It's the same as writing multiple operations in an if else statement.
The right answer is: it depends. Most of the time, they are about the same speed and you don't need to care. But if $context['test'] contains a large amount of data, snippet 2 is much faster than snippet 1.
In PHP 7.4 using nested ternaries without explicit parentheses will throw a deprecation warning. In PHP 8.0 it will become a compile-time error instead.
The syntax for the ternary operator is as follows. Syntax: (Condition) ? (Statement1) : (Statement2); Condition: It is the expression to be evaluated and returns a boolean value.
Because what you've written is the same as:
echo (true ? 1 : true) ? 2 : 3;
and as you know 1 is evaluated to true
.
What you expect is:
echo (true) ? 1 : (true ? 2 : 3);
So always use braces to avoid such confusions.
As was already written, ternary expressions are left associative in PHP. This means that at first will be executed the first one from the left, then the second and so on.
Separate second ternary clause with parentheses.
echo true ? 1 : (true ? 2 : 3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With