了解嵌套的PHP三元运算符 [英] Understanding nested PHP ternary operator
本文介绍了了解嵌套的PHP三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不明白该输出("four
")是怎么来的?
I dont understand how that output ("four
") comes?
$a = 2;
echo
$a == 1 ? 'one' :
$a == 2 ? 'two' :
$a == 3 ? 'three' :
$a == 5 ? 'four' :
'other'
;
// prints 'four'
我不明白为什么打印"four
".
I don't understand why "four
" gets printed.
推荐答案
您需要将三元条件括起来:
You need to bracket the ternary conditionals:
<?php
for ($a=0; $a < 7; $a++) {
echo (
$a == 1 ? 'one' :
($a == 2 ? 'two' :
($a == 3 ? 'three' :
($a == 5 ? 'four' : 'other'))));
echo "\n";
// prints 'four'
}
exit;
?>
返回:
other
one
two
three
other
four
other
如您所愿.
请参见 PHP三元运算符帮助,在三元运算符"底部的注释.
See the note at the bottom of "Ternary operators" at PHP Ternary operator help.
表达式从左到右进行求值.因此,您实际上得到了:
The expressions are being evaluated left to right. So you are actually getting:
echo (
((($a == 1 ? 'one' : $a == 2)
? 'two' : $a == 3) ? 'three' :
$a == 5) ? 'four' : 'other');
因此对于$a=2
,您将得到:
echo (
((($a==2) ? 'two' : $a == 3) ? 'three' :
$a == 5) ? 'four' : 'other');
然后
echo (
((true ? 'two' : $a == 3) ? 'three' :
$a == 5) ? 'four' : 'other');
然后
echo (
('two' ? 'three' : $a == 5) ? 'four' : 'other');
然后
echo (
'three' ? 'four' : 'other');
以及echo 'four'
.
请记住,PHP是动态类型的,并将任何非零,非null值都视为TRUE.
Remember that PHP is dynamically typed and treats any non-zero non-null values as TRUE.
这篇关于了解嵌套的PHP三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文