PHP multiple ternary operator not working as expected

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.

Leave a Comment