?: beyond the ternary operator (PHP surprise)

Here is a famous ternary operator in C:

condition ? A : B

It can also be conveniently chained:

condition1 ? A : condition2 ? B : condition3 ? C : D

The evaluation of the conditions are in turns: condition1, condition2, condition 3 …

However I had a surprise the other day with PHP:

condition1 ? A : condition2 ? B : condition3 ? C : D

evaluates as:

((condition1 ? A : condition2) ? B : condition3) ? C : D

rather than:

condition1 ? A : (condition2 ? B : (condition3 ? C : D))
This entry was posted in programming. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *