PHP ternary operator

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

conclusion: three

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

conclusion: two

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

+4
source share
3 answers

This is due to the fact that the ternary operator ( ?:) is left associative , so this is how it is evaluated:

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

So, 1 == 1TRUEmeans then that:

"one" ? "two" : "three"

And "one"TRUE, so the output will be:

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

Remember to use parentheses when the result of the operation may be unclear.

now output one

+6
source

, .

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

,

0
source

All Articles