嵌套三元语句
我想知道为什么这会很奇怪。我知道区别在于分组,但是比较重要吗?
$i = 0;
foreach ($items as $item) {
echo ($i == 0) ? 'first_row' : ($i == sizeof($feedbacks)-2) ? 'last_row' : 'none';
$i++;
}
返回
last_row
none
none
last_row
和
$i = 0;
foreach ($items as $item) {
echo ($i == 0) ? 'first_row' : (($i == sizeof($feedbacks)-2) ? 'last_row' : 'none');
$i++;
}
正确返回
first_row
none
none
last_row
为什么有区别?
I wonder why this works strange. I understand that the difference is grouping, but does it matter in comparison?
$i = 0;
foreach ($items as $item) {
echo ($i == 0) ? 'first_row' : ($i == sizeof($feedbacks)-2) ? 'last_row' : 'none';
$i++;
}
returns
last_row
none
none
last_row
and
$i = 0;
foreach ($items as $item) {
echo ($i == 0) ? 'first_row' : (($i == sizeof($feedbacks)-2) ? 'last_row' : 'none');
$i++;
}
returns it correctly
first_row
none
none
last_row
Why is there a difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要使用基于您的代码的解释,缩小版本将是:
在 PHP 中,这相当于编写:
第一次,
$i
的值为0
,因此第一个三元数返回'first_row'
并且该字符串用作第二个三元数的条件 - 在布尔上下文中计算结果为true
- 因此'last_row'
返回。如果重新组合:
那么第一个三元的结果不会干扰第二个三元。
To use an explanation based on your code, a scaled down version would be:
In PHP, this is equivalent to writing:
On the first go,
$i
has the value of0
, so the first ternary returns'first_row'
and that string is used as the conditional for the second ternary -- which in boolean context evaluates totrue
-- hence'last_row'
is returned.If you regroup it:
then the result of the first ternary will not interfere with the second ternary.
来自官方 PHP 文档 :
显然,即使 PHP 的三元运算符(及其大部分语法)基于 C ,出于某种原因,PHP 决定使其左关联,然而在 C 和基于它的大多数其他语言中,三元运算符是右结合的:
C:
Perl:
Java:
JavaScript:
PHP:
所以,是的,我认为我们可以有把握地得出这样的结论:PHP 在这方面(也)只是简单的倒退。
From the official PHP documentation:
Apparently, even though PHP's ternary operator (and much of its syntax otherwise) is based on C, for some reason PHP decided to make it left-associative, whereas in C and most other languages based on it, the ternary operator is right-associative:
C:
Perl:
Java:
JavaScript:
PHP:
So, yeah, I think we can safely conclude that PHP is just plain ass-backwards in (also) this respect.
请参阅 php.net 上的示例 3:
重要的部分是:
See example 3 on php.net:
The important part being:
看看JRL提供的答案。为了更清楚地了解您的示例发生的情况,您应该了解您的表达式是这样计算的:
因此,当
$i == 0
时,您的语句基本上变成这样:Since
'first_row'< /code> 计算结果为
true
,您的'last_row'
是$i == 0
时返回的结果。当 $i 不等于 0 时,你的语句基本上变成这样:Take a look at the answer provided by JRL. To be more clear about what is happening with your example you should understand that your expression is evaluated as such:
So when
$i == 0
your statement essentially becomes this:Since
'first_row'
evaluates totrue
your'last_row'
is the result returned when$i == 0
. When$i
does not equal zero your statement essentially becomes this: