2011-10-04 48 views
8

我不知道爲什麼這個工程很奇怪。我明白不同之處在於分組,但相比之下它有什麼關係?嵌套三元報表

$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 

爲什麼是有區別嗎?

回答

13

使用基於代碼的解釋,一個縮小版本將是:

for ($i=0; $i<5; $i++) { 
    echo $i == 0 ? 'first_row' : $i == 4 ? 'last_row' : 'none'; 
} 

在PHP中,這等同於書寫:

for ($i=0; $i<5; $i++) { 
    echo ($i == 0 ? 'first_row' : $i == 4) ? 'last_row' : 'none'; 
} 

在第一次去,$i0價值,所以第一三元回報'first_row'並且該字符串用作第二個三元組的條件 - 在布爾上下文中計算爲true - 因此返回'last_row'

如果重組是:

for ($i=0; $i<5; $i++) { 
    echo $i == 0 ? 'first_row' : ($i == 4 ? 'last_row' : 'none'); 
} 

然後第一三元的結果不會與第二三元干涉。

3

example 3 on php.net

<?php 
// on first glance, the following appears to output 'true' 
echo (true?'true':false?'t':'f'); 

// however, the actual output of the above is 't' 
// this is because ternary expressions are evaluated from left to right 

// the following is a more obvious version of the same code as above 
echo ((true ? 'true' : false) ? 't' : 'f'); 

// here, you can see that the first expression is evaluated to 'true', which 
// in turn evaluates to (bool)true, thus returning the true branch of the 
// second ternary expression. 
?> 

最重要的部分是:

這是因爲三元表達式從左至右

4

official PHP documentation評價:

」建議您避免「疊加」三元表達式。在一個語句中使用多個三元運算符時,PHP的行爲是無明顯的」

顯然,即使PHP的三元操作符(和許多否則其語法)是基於C,出於某種原因PHP決定make it left-associative,而在C和大多數其他語言在此基礎上,the ternary operator is right-associative

C:

$ cat /tmp/foo.c 
#include <stdio.h> 
void main (void) { printf("%s\n", (1 ? "foo" : 0 ? "bar" : "baz")); } 

$ gcc -o /tmp/foo /tmp/foo.c; /tmp/foo 
foo 

的Perl:

$ perl -e 'print (1 ? "foo" : 0 ? "bar" : "baz") . "\n";' 
foo 

的Java:

$ cat /tmp/foo.java 
public class foo { public static void main(String[] args) { 
    System.out.println((true ? "foo" : false ? "bar" : "baz")); 
} } 

$ javac -d /tmp /tmp/foo.java; java -cp /tmp foo 
foo 

的JavaScript:

$ cat /tmp/foo.js 
print(1 ? "foo" : 0 ? "bar" : "baz"); 

$ rhino -f /tmp/foo.js 
foo 

PHP:

$ php -r 'echo (1 ? "foo" : 0 ? "bar" : "baz") . "\n";' 
bar 

所以,是的,我認爲我們可以有把握地得出結論,PHP在這方面(也)只是簡單的屁股倒退。

+0

在upvoting之間緩解其他語言的不錯的例子和downvoting無視php:/ / –

0

看看JRL提供的答案。要了解什麼是你的榜樣發生的事情,你應該明白,你的表情是這樣評價更加清晰:

echo (($i == 0) ? 'first_row' : ($i == sizeof($feedbacks)-2)) ? 'last_row' : 'none'; 

所以當$i == 0你的聲明從本質上變成這樣:

echo 'first_row' ? 'last_row' : 'none'; 

由於'first_row'評估爲true您的'last_row'$i == 0時返回的結果。當$i不等於零的聲明從本質上變成這樣:

echo ($i == sizeof($feedbacks)-2) ? 'last_row' : 'none';