'Nested PHP ternary operator precedence
Yes, I know this is very bad code, but I'd still like to understand it:
$out = $a > 9 && $a < 15 ? "option1" : $a < 5 ? "option2" : "option3";
$out = $a > 9 && $a < 15 ? "option1" : ($a < 5 ? "option2" : "option3");
If $a is 11, then the result of the 1st line is "option 2", but in the 2nd line, the result is "option 1" - what effect is the pair of brackets having?
Solution 1:[1]
The unparenthesized code you've got is parsed as:
$out = (
(
($a < 9 && $a < 15)
? ("option1")
: ($a < 5)
)
? ( "option2" )
: ( "option3" )
);
This is because PHP's ternary operator is left-associative. This is the exact opposite of the way it works in every other language, and ends up interpreting chained ternary expressions in a surprising (and almost always useless!) way. This is widely regarded as a bug, but one that's "too old to fix", much like some similar precedence issues with C's binary operators.
Adding the parentheses in your second expression yields the intended:
$out = (
($a > 9 && $a < 15)
? ("option1")
: (
($a < 5)
? ("option2")
: ("option3")
)
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
