And*_*ndy 6 php arrays compare
第一个例子:
$x = array("a" => 1, "b" => 2);
$y = array("b" => 1, "a" => 2);
$xLessY = ($x < $y);
$xGreaterY = ($x > $y);
var_dump($xLessY, $xGreaterY);
Run Code Online (Sandbox Code Playgroud)
结果:$ xLessY = true,$ xGreaterY = true
第二个例子:
$x = array("a" => 2, "b" => 1);
$y = array("b" => 2, "a" => 1);
$xLessY = ($x < $y);
$xGreaterY = ($x > $y);
var_dump($xLessY, $xGreaterY);
Run Code Online (Sandbox Code Playgroud)
结果:$ xLessY = false,$ xGreaterY = false
根据http://docs.php.net/manual/en/language.operators.comparison.php上的文档:
如果在操作数2中找不到操作数1的键,则数组是无法比较的,否则 - 按值比较值
在我们的例子中,数组$ x中的每个键都存在于数组$ y中,因此$ x和$ y是可比较的.另请参阅文档中的示例:
// 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
}
Run Code Online (Sandbox Code Playgroud)
这种行为非常奇怪:$ x小于$ y,同时$ x大于$ y(第一个例子),两个数组相当.
我认为这是因为php始终从符号'<'的一个明确方面开始比较.我的意思是:for($ x <$ y)php将$ x作为操作数1,对于($ x> $ y),它需要$ y作为操作数1.虽然我在文档中没有找到任何关于此行为的信息.
你对此有何看法?
| 归档时间: |
|
| 查看次数: |
386 次 |
| 最近记录: |