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?
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?
Because what you've written is the same as:
and as you know 1 is evaluated to
true
.What you expect is:
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.
from the docs
Use parentheses when in doubt.
The ternary operator in PHP is left-associative in contrast to other languages and does not work as expected.