PHP multiple ternary operator not working as expected

Separate second ternary clause with parentheses.

echo true ? 1 : (true ? 2 : 3);

Because what you've written is the same as:

echo (true ? 1 : true) ? 2 : 3;

and as you know 1 is evaluated to true.

What you expect is:

echo (true) ? 1 : (true ? 2 : 3);

So always use braces to avoid such confusions.

As was already written, ternary expressions are left associative in PHP. This means that at first will be executed the first one from the left, then the second and so on.


Use parentheses when in doubt.

The ternary operator in PHP is left-associative in contrast to other languages and does not work as expected.