The code my friend sends me is:
echo '1+1='.(1+1==2?2:1+2==2?3:2);
Why is it 3?
PHP's evaluation of the ternary (or conditional) operator is a bit different from that of other languages.
1+1==2 ? 2 : 1+2==2 ? 3 : 2
Most languages (e.g. JavaScript) would evaluate this as:
(1+1==2) ? (2) : ( (1+2==2) ? (3) : (2) ) => 2
PHP, however, evaluates this as:
( (1+1==2) ? (2) : (1+2==2) ) ? (3) : (2) => 3
So because (1+1==2)
evaluates to true, the result of the first ternary expression evaluates to 2
, and that result is then passed to the second ternary expression, which evaluates to 3
.
This behavior is alluded to in the documentation:
It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious…
The Wikipedia article on the ?:
operator also mentions this:
Due to an unfortunate error in the language grammar, the implementation of ?: in PHP uses the incorrect associativity when compared to other languages…
The reason is that nesting two conditional operators produces an oversized condition with the last two options as its branches:
c1 ? o1 : c2 ? o2 : o3
is really((c1 ? o1 : c2) ? o2 : o3)
. This is acknowledged and will probably not change.
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