質問

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?

役に立ちましたか?

解決 2

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");

他のヒント

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")
    )
);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top