了解嵌套 PHP 三元运算符
我不明白这个输出(“four
”)是如何产生的?
$a = 2;
echo
$a == 1 ? 'one' :
$a == 2 ? 'two' :
$a == 3 ? 'three' :
$a == 5 ? 'four' :
'other'
;
// prints 'four'
我不明白为什么会打印“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'
I don't understand why "four
" gets printed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要将三元条件:
returns:
如您所期望的括起来。
请参阅 PHP 三元运算符帮助 中“三元运算符”底部的注释。
表达式从左到右进行计算。所以你实际上得到的是:
所以对于
$a=2
,你得到:然后然后
然后
然后
然后所以
echo 'four'
。请记住,PHP 是动态类型的,并将任何非零非空值视为 TRUE。
You need to bracket the ternary conditionals:
returns:
as you'd expect.
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:
So for
$a=2
, you get:and then
and then
and then
and so
echo 'four'
.Remember that PHP is dynamically typed and treats any non-zero non-null values as TRUE.
在PHP 手册中的比较运算符页面上,他们解释了 PHP 的行为是“不明显”嵌套(堆叠)时三元运算符。
您编写的代码如下所示:
由于
$a
为 2,并且'two'
和'third'
也都为 TRUE,结果是“four
”,因为您不再比较'four'
是否为 TRUE。如果你想改变它,你必须把括号放在不同的地方[也被注意到:BeingSimpler和MGwynne]:
On the Comparison Operators page in the PHP Manual they explain that PHP's behavior is "non-obvious" when nesting (stacking) ternary operators.
The code you've written is like this:
As
$a
is 2 and both'two'
and'three'
are TRUE as well, you get "four
" as the result, as you don't compare any longer if'four'
is TRUE or not.If you want to change that, you have to put the brackets at different places [also noted by: BeingSimpler and MGwynne]:
分组条件有问题,只需要加括号分隔即可。
解决了。
Problem with grouping conditions, just need to add brackets to separate them.
Solved.
这是我想出的方法来帮助自己理解三元运算符的左结合性与右结合性。
这与以下情况相反:
如果您注意到,在 PHP 示例中,最内层的表达式位于左侧,而在第二个示例中,最内层的表达式位于右侧。每个步骤都会评估下一个最里面的表达式,直到得到一个结果。如果您要在 PHP 中嵌套三元运算,括号显然非常重要!
This is what I came up with to help myself understand left vs. right associativity for the ternary operator.
This is as opposed to:
If you notice, in the PHP example, the innermost expression is on the left, and on the second example, the innermost expression is on the right. Each step evaluates the next innermost expression until there is a single result. Parenthesis are clearly very important if you're going to nest ternary operations in PHP!