PHP multiple ternary operator not working as expected

谁都会走 提交于 2019-12-17 06:15:04

问题


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.
?>



回答5:


In your case, you should consider the priority of executing statements.

Use following code:

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

For example,

$a = 2;
$b = 1;
$c = 0;

$result1 = $a ** $b * $c;
// is not equal
$result2 = $a ** ($b * $c);

Are you have used parentheses in expressions in mathematics? - Then, that the result, depending on the execution priority, is not the same. In your case, ternary operators are written without priorities. Let the interpreter understand in what order to perform operations using parentheses.



来源:https://stackoverflow.com/questions/14214427/php-multiple-ternary-operator-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!