PHP ternary operator not working as expected

2019-01-09 09:44发布

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?

4条回答
ら.Afraid
2楼-- · 2019-01-09 10:25

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.

查看更多
时光不老,我们不散
3楼-- · 2019-01-09 10:28

Separate second ternary clause with parentheses.

echo true ? 1 : (true ? 2 : 3);
查看更多
Viruses.
4楼-- · 2019-01-09 10:29

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.
?>
查看更多
我想做一个坏孩纸
5楼-- · 2019-01-09 10:32

Use parentheses when in doubt.

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

查看更多
登录 后发表回答