PHP检查数组是否相同?

时间:2011-11-27 03:35:56

标签: php

我正在寻找一种方法来检查两个数组是否相同,例如

  $a = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);
$b = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);

这两个是相同的,但是如果单个值被更改,它将返回false,我知道我可以编写一个函数,但是有一个已经构建了吗?

2 个答案:

答案 0 :(得分:22)

如果订单无关紧要,您可以使用$a == $b;如果订单无关紧要,您可以使用$a === $b

例如:

$a = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);
$b = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);
$c = array(
    '3' => 14,
    '1' => 12,
    '6' => 11
);
$d = array(
    '1' => 11,
    '3' => 14,
    '6' => 11
);

$a == $b;   // evaluates to true
$a === $b;  // evaluates to true
$a == $c;   // evaluates to true
$a === $c;  // evaluates to false
$a == $d;   // evaluates to false
$a === $d;  // evaluates to false

答案 1 :(得分:12)

您可以使用

$a === $b // or $a == $b

用法示例:

<?php
$a = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);
$b = array(
    '1' => 12,
    '3' => 14,
    '6' => 11
);
echo ($a === $b) ? 'they\'re same' : 'they\'re different';

echo "\n";
$b['1'] = 11;

echo ($a === $b) ? 'they\'re same' : 'they\'re different';

将返回

they're same
they're different

demo