I'm struggling to understand why the following code is echoing out 'FOO2' when i'm expecting 'FOO1'
$tmp = 'foo1';
echo $tmp == 'foo1' ? 'FOO1' : $tmp == 'foo2' ? 'FOO2' : 'NO FOO';
$tmp = 'foo1';
echo $tmp == 'foo1' ? 'FOO1' : ($tmp == 'foo2' ? 'FOO2' : 'NO FOO');
basically PHP breaks this down to:
$tmp = 'foo1';
echo ($tmp == 'foo1' ? 'FOO1' : $tmp == 'foo2') ? 'FOO2' : 'NO FOO';
the part in parentheses will return FOO1
which evaluates to TRUE
so the second conditional statement essentially is TRUE? 'FOO2': 'NO FOO';
TRUE? 'FOO2': 'NO FOO';
– which in turn always evaluates to 'FOO2'
Note: This is different from C ternary operator associativity
$tmp = 'foo1';
if($tmp == 'foo1') echo 'FOO1';
else if($tmp == 'foo2') echo 'FOO2';
As you have just found out, ternary operators are a minefield of confusion, especially when you try to
nest
stack them. Don't do it!
Edit:
The PHP manual also recommends not stacking ternary operators:-
It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:
See example 3 on this page of the PHP Manual
$tmp = 'foo1';
echo $tmp == 'foo1' ? 'FOO1' : ($tmp == 'foo2' ? 'FOO2' : 'NO FOO');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.