php shorthand if
I'm struggling to understand why the following code is echoing out 'FOO2' when i'm expecting 'FOO1'
$t开发者_C百科mp = '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';
– 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');
精彩评论