第一個例子:比較陣列 - 有趣的行爲
$x = array("a" => 1, "b" => 2);
$y = array("b" => 1, "a" => 2);
$xLessY = ($x < $y);
$xGreaterY = ($x > $y);
var_dump($xLessY, $xGreaterY);
結果:$ xLessY = 真正,$ xGreaterY = 真正
第二個例子:
$x = array("a" => 2, "b" => 1);
$y = array("b" => 2, "a" => 1);
$xLessY = ($x < $y);
$xGreaterY = ($x > $y);
var_dump($xLessY, $xGreaterY);
結果:$ xLessY = 假,$ xGreaterY = 假
上http://docs.php.net/manual/en/language.operators.comparison.php根據文檔:
如果從操作數1鑰匙沒有 操作數2,則發現陣列是 不可比否則, - 比較 按值計算
在我們的例子中,數組$ x中的每個鍵都存在於數組$ y中,所以$ x和$ y是comp耕地。 參見例如,從文檔:
// Arrays are compared like this with standard comparison operators
function standard_array_compare($op1, $op2)
{
if (count($op1) < count($op2)) {
return -1; // $op1 < $op2
} elseif (count($op1) > count($op2)) {
return 1; // $op1 > $op2
}
foreach ($op1 as $key => $val) {
if (!array_key_exists($key, $op2)) {
return null; // uncomparable
} elseif ($val < $op2[$key]) {
return -1;
} elseif ($val > $op2[$key]) {
return 1;
}
}
return 0; // $op1 == $op2
}
這種行爲是非常奇怪的:$ x小於$ y和在同一時間$ x大於$ Y(第一個例子)和兩個數組具有可比性更大。
我認爲這是因爲PHP總是從符號'<'的一個確定的一邊開始比較。我的意思是:for($ x < $ y)php以$ x作爲操作數1,對於($ x> $ y)它需要$ y作爲操作數1.儘管我在文檔中沒有找到有關此行爲的任何信息。
你對此有何看法?
我懷疑你可能是正確的,無論哪個值在'<'的最尖端被用作第一個操作數。當然,如果你看看PHP源代碼,你可以找到答案... – 2011-06-25 20:42:51