Search code examples
phpconditional-operator

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

  • The first line is parsed like so:

    $out = ($a > 9 && $a < 15 ? "option1" : $a < 5) ? "option2" : "option3";
    

    Which is equivalent to the following (when $a == 11):

    $out = "option1" ? "option2" : "option3";
    

    "option1" coerced to boolean is true, so the above evaluates to "option2".

    The second is being parsed as you would expect:

    $out = ($a > 9 && $a < 15) ? "option1" : ($a < 5 ? "option2" : "option3");