The Ternary Operator in PHP [duplicate]

2019-01-28 05:43发布

This question already has an answer here:

$chow = 3;
echo ($chow == 1) ? "one" : ($chow == 2) ? "two" : "three";

output: three

$chow = 1;
echo ($chow == 1) ? "one" : ($chow == 2) ? "two" : "three";

output: two

Can anyone explain why the output is "two" when $chow = 1 instead of "one"?

3条回答
ら.Afraid
2楼-- · 2019-01-28 06:11
$chow = 1;
echo ($chow == 1) ? "one" : (($chow == 2) ? "two" : "three");

remember to use brackets when result of operation can be unclear

now output is one

查看更多
戒情不戒烟
3楼-- · 2019-01-28 06:13

The operator is confused, you need to put brackets around your second codition. use the code below

$chow = 1;
echo ($chow == 1) ? "one" : (($chow == 2) ? "two" : "three"); //returns 1

Hope this helps you

查看更多
女痞
4楼-- · 2019-01-28 06:26

This is because the ternary operator (?:) is left associative so this is how it's getting evaluated:

((1 == 1) ? "one" : (1 == 2)) ? "two" : "three"

So 1 == 1 -> TRUE means that then it's:

"one" ? "two" : "three"

And "one" -> TRUE so the output will be:

two
查看更多
登录 后发表回答