PHP ternary operator not working as expected

2019-01-09 09:32发布

问题:

Why is this printing 2?

echo true ? 1 : true ? 2 : 3;

With my understanding, it should print 1.

Why is it not working as expected?

回答1:

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.



回答2:

Separate second ternary clause with parentheses.

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


回答3:

Use parentheses when in doubt.

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



回答4:

from the docs

Example #3 Non-obvious Ternary Behaviour
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>