Let’s first look at a ternary operation formula:
Copy the code The code is as follows:
$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 The code is as follows:
$a<$b => true => 'xx' ==> End
Then the final result is 'xx', and subsequent operations will be ignored.
What is surprising is that the final result of the above code in PHP is 'zz' '...Oh my god, what's going on? Isn't this cheating...
I followed the old rules and had to ask Google for advice. I was told that the ternary operation of PHP is left associative... and I suddenly understood.
I add two brackets to the above code:
Copy the code The code is as follows:
< ?php
$a=1;$b=2;$c=3;$d=4;
echo (($a<$b?'xx':$a<$c)?'yy ':$a<$d)?'zz':'oo';
?>
It is clear at a glance, this is the operation logic of php:
Copy code The code is as follows:
$a<$b => true => 'xx' => true => ; 'yy' => true => 'zz' => End
This involves two types of conversion processes, namely 'xx' => true and 'xx' => true.
I don’t know if this process is a pain in the ass, it’s really hard to understand...
Finally, go back to the above code again and change it into a right combine like C :
Copy code The code is as follows:
$a=1;$b =2;$c=3;$d=4;
echo $a<$b?'xx':($a<$c?'yy':($a<$d?'zz':' oo'));
// Just change the position of the brackets. You cannot omit brackets in PHP
?>
http://www.bkjia.com/PHPjc/324777.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324777.htmlTechArticleFirst look at a ternary operation formula: Copy the code as follows: ?php $a=1;$b= 2;$c=3;$d=4; echo $a$b?'xx':$a$c?'yy':$a$d?'zz':'oo'; ? Generally follow other languages ( Such as C or Java) rules, the above...