开发者

php shorthand if

开发者 https://www.devze.com 2023-03-21 08:52 出处:网络
I\'m struggling to understand why the following code is echoing out \'FOO2\' when i\'m expecting \'FOO1\'

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');
0

精彩评论

暂无评论...
验证码 换一张
取 消