PHP nested conditional operator bug?

别来无恙 提交于 2019-12-01 19:02:27

It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious

From the PHP Manual under "Non-obvious Ternary Behaviour".

Ternary operators are evaluated left to right, so unless you add it the braces it doesn't behave as you expect. The following would work though,

return (true ? "a" : (false ? "b" : "c"));

Suspect it's evaluating (true ? 'a' : false) as the input to the second ternary operator and interpreting 'a' as true. Try bracketing appropriately.

order of operations:

>>> return true ? 'a' : false ? 'b': 'c';
'b'
>>> return true ? 'a' : (false ? 'b': 'c');
'a'

Let me explain in same way it was explained to me. But you have to pay attention in parenthesis to understand what is happening.

The PHP

The PHP code below

true ? "a" : false ? "b" : "c"

Is equivalent to:

(true ? "a" : false) ? "b" : "c"

Another languages

The code below

true ? "a" : false ? "b" : "c"

Is equivalent to:

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