Skip to content
Advertisement

Nested PHP ternary operator precedence

Yes, I know this is very bad code, but I’d still like to understand it:

JavaScript

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?

Advertisement

Answer

The first line is parsed like so:

JavaScript

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

JavaScript

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

The second is being parsed as you would expect:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement