SoFunction
Updated on 2025-03-10

Introduction to the binding nature of PHP ternary operators

Let's look at a ternary operation formula:

Copy the codeThe code is 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 the codeThe code is as follows:

$a<$b => true => 'xx' ==> End

Then the final result is 'xx', and the subsequent operations will be ignored.
However, what is surprising is that the final result of php calculation of the above code is 'zz'... I'm sorry, what's the situation? Isn't this a scam...
The old rules have to ask Google Jiang for advice, but I was told that the ternary operation of PHP was actually combined to the left... so I suddenly realized it.
I'll add two brackets to the above code:

Copy the codeThe 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's clear at a glance, this is the operation logic of php:

Copy the codeThe code is as follows:

$a<$b => true => 'xx' => true => 'yy' => true => 'zz' => end

This involves two types of transformation processes, namely 'xx' => true and 'xx' => true.
I don't know if this process is painful, it is really hard to understand...
Finally, go back to the above code again and turn it into a right-to-right combination like C:

Copy the codeThe code is as follows:

<?php
$a=1;$b=2;$c=3;$d=4;
echo $a<$b?'xx':($a<$c?'yy':($a<$d?'zz':'oo'));
// Just change the brackets, you can't save the brackets in php
?>