Reputation: 409
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';
Upvotes: 0
Views: 4306
Reputation: 265161
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
Upvotes: 4
Reputation: 18440
$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
Upvotes: 1
Reputation: 1119
$tmp = 'foo1';
echo $tmp == 'foo1' ? 'FOO1' : ($tmp == 'foo2' ? 'FOO2' : 'NO FOO');
Upvotes: 0
Reputation: 2193
$tmp = 'foo1';
echo $tmp == 'foo1' ? 'FOO1' : ($tmp == 'foo2' ? 'FOO2' : 'NO FOO');
Upvotes: 8