Let's look at a ternary formula:
Copy Code code as follows:
<?php
$a =1 $b =2; $c =3; $d = 4;
echo $a < $b? ' XX ': $a < $c? ' YY ': $a < $d? ' ZZ ': ' OO ';
?>
Generally according to the rules of other languages (such as C or Java), the operation logic of the above code is:
Copy Code code as follows:
$a < $b => true => ' xx ' ==> end
Then the final result is ' xx ', and the subsequent operation will be ignored.
Surprisingly, however, the results of the above code in PHP are ' zz ' ... I rub, what situation, this does not pit dad ...
The old rules, had to ask Google sauce, the results were told that PHP ternary operation is left-bound ... Then suddenly enlightened.
I add two parentheses to the code above:
Copy Code code as follows:
<?php
$a =1 $b =2; $c =3; $d = 4;
Echo ($a < $b? XX ': $a < $c)? ' YY ': $a < $d)? ' ZZ ': ' OO ';
?>
At a glance, this is the logic of the PHP operation:
Copy Code code as follows:
$a < $b => true => ' xx ' => true => ' yy ' => true => ' zz ' => end
This involves two types of conversion processes, that is, ' xx ' => true and ' xx ' => true.
I do not know if this process is the egg pain, it is really difficult to understand ...
Finally go back to the code and turn it into the right combination like C:
Copy Code code as follows:
<?php
$a =1; $b =2; $c =3; $d = 4;
Echo $a < $b? ' XX ':($a < $c? ' YY ':($a < $d? ' ZZ ': ' oo '));
//parentheses to replace the position on the line, PHP can not be in parentheses
?>