Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/235.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-检查两个数组是否相等_Php_Arrays - Fatal编程技术网

PHP-检查两个数组是否相等

PHP-检查两个数组是否相等,php,arrays,Php,Arrays,我想检查两个数组是否相等。我的意思是:相同的大小,相同的索引,相同的值。我该怎么做 使用==根据用户的建议,如果数组中至少有一个元素不同,我希望下面的内容会打印enter,但事实上并非如此 if (($_POST['atlOriginal'] !== $oldAtlPosition) or ($_POST['atl'] !== $aext) or ($_POST['sidesOriginal'] !== $oldSidePosition) or ($_POST['s

我想检查两个数组是否相等。我的意思是:相同的大小,相同的索引,相同的值。我该怎么做

使用
==
根据用户的建议,如果数组中至少有一个元素不同,我希望下面的内容会打印enter,但事实上并非如此

if (($_POST['atlOriginal'] !== $oldAtlPosition) 
    or ($_POST['atl'] !== $aext) 
    or ($_POST['sidesOriginal'] !== $oldSidePosition) 
    or ($_POST['sidesOriginal'] !== $sideext)) {

    echo "enter";
}

array_diff-计算数组的差异

array1
与一个或多个其他数组进行比较,并返回
array1
中不存在于任何其他数组中的值


将它们作为其他值进行比较:

if($array_a == $array_b) {
  //they are the same
}
您可以在此处阅读有关所有数组运算符的信息: 例如,请注意,
==
还检查数组中元素的类型和顺序是否相同

$arraysAreEqual = ($a == $b); // TRUE if $a and $b have the same key/value pairs.
$arraysAreEqual = ($a === $b); // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.

编辑

不等式运算符是
=而非标识运算符为
==以匹配相等项

运算符
=
和标识运算符
==

尝试序列化。这也将检查嵌套子阵列

$foo =serialize($array_foo);
$bar =serialize($array_bar);
if ($foo == $bar) echo "Foo and bar are equal";
根据

注意:接受的答案适用于关联数组,但不适用于索引数组(解释如下)。如果您想比较它们中的任何一个,请使用此解决方案。此外,此函数可能不适用于多维数组(由于数组_diff函数的性质)

使用
$a==$b
$a===$b
测试两个索引数组(元素顺序不同)失败,例如:

<?php
    (array("x","y") == array("y","x")) === false;
?>

添加了比较阵列大小(super_ton建议),因为这可能会提高速度。

===将不起作用,因为它是一个语法错误。正确的方法是
==(不是三个“等于”符号)

单向:(实现“视为等于”)

这种方式允许其成员顺序不同的关联数组,例如,除了php之外,在每种语言中它们都被认为是相等的:)


检查相等性的另一种方法(无论值顺序如何)的工作原理是使用,如下所示:

$array1 = array(2,5,3);
$array2 = array(5,2,3);
if($array1 === array_intersect($array1, $array2) && $array2 === array_intersect($array2, $array1)) {
    echo 'Equal';
} else {
    echo 'Not equal';
}
以下是一个同样适用于多维数组的版本,使用:


使用php函数array_diff(array1,array2)

它将返回数组之间的差异。如果它是空的,那么它们是相等的

例如:

$array1 = array(
    'a' => 'value1',

    'b' => 'value2',

    'c' => 'value3'
 );

$array2 = array(
    'a' => 'value1',

    'b' => 'value2',

    'c' => 'value4'
 );

$diff = array_diff(array1, array2);

var_dump($diff); 

//it will print array = (0 => ['c'] => 'value4' ) 
例2:

$array1 = array(
    'a' => 'value1',

    'b' => 'value2',

    'c' => 'value3',
 );

$array2 = array(
    'a' => 'value1',

    'b' => 'value2',

    'c' => 'value3',
 );

$diff = array_diff(array1, array2);

var_dump($diff); 

//it will print empty; 

简短的解决方案,即使在密钥顺序不同的阵列中也能使用:

public static function arrays_are_equal($array1, $array2)
{
    array_multisort($array1);
    array_multisort($array2);
    return ( serialize($array1) === serialize($array2) );
}

数组上的语法问题

$array1 = array(
    'a' => 'value1',
    'b' => 'value2',
    'c' => 'value3',
 );

$array2 = array(
    'a' => 'value1',
    'b' => 'value2',
    'c' => 'value3',
 );

$diff = array_diff($array1, $array2);

var_dump($diff); 
从我的观点来看,使用array_diff比array_intersect更好,因为在这种性质的检查中,返回的差异通常小于相似性,这样bool转换就不需要太多内存


编辑请注意,此解决方案适用于普通数组,并补充了上面发布的仅对字典有效的==和===解决方案。

如果要检查非关联数组,以下是解决方案:

$a = ['blog', 'company'];
$b = ['company', 'blog'];

(count(array_unique(array_merge($a, $b))) === count($a)) ? 'Equals' : 'Not Equals';
// Equals

下面是一个如何与数组进行比较并获得它们之间的差异的示例

$array1 = ['1' => 'XXX', 'second' => [
            'a' => ['test' => '2'],
            'b' => 'test'
        ], 'b' => ['no test']];

        $array2 = [
            '1' => 'XX',
            'second' => [
                'a' => ['test' => '5', 'z' => 5],
                'b' => 'test'
            ],
            'test'
        ];


        function compareArrayValues($arrayOne, $arrayTwo, &$diff = [], $reversed = false)
        {
            foreach ($arrayOne as $key => $val) {
                if (!isset($arrayTwo[$key])) {
                    $diff[$key] = 'MISSING IN ' . ($reversed ? 'FIRST' : 'SECOND');
                } else if (is_array($val) && (json_encode($arrayOne[$key]) !== json_encode($arrayTwo[$key]))) {
                    compareArrayValues($arrayOne[$key], $arrayTwo[$key], $diff[$key], $reversed);
                } else if ($arrayOne[$key] !== $arrayTwo[$key]) {
                    $diff[$key] = 'DIFFERENT';
                }
            }
        }

        $diff = [];
        $diffSecond = [];

        compareArrayValues($array1, $array2, $diff);
        compareArrayValues($array2, $array1, $diffSecond, true);

        print_r($diff);
        print_r($diffSecond);

        print_r(array_merge($diff, $diffSecond));
结果:

Array
(
    [0] => DIFFERENT
    [second] => Array
        (
            [a] => Array
                (
                    [test] => DIFFERENT
                    [z] => MISSING IN FIRST
                )

        )

    [b] => MISSING IN SECOND
    [1] => DIFFERENT
    [2] => MISSING IN FIRST
)

下面的解决方案与自定义相等函数一起使用,您可以将其作为回调传递。注意,它不检查数组顺序

trait AssertTrait
{
    /**
     * Determine if two arrays have the same elements, possibly in different orders. Elements comparison function must be passed as argument.
     *
     * @param array<mixed> $expected
     * @param array<mixed> $actual
     *
     * @throws InvalidArgumentException
     */
    public static function assertArraysContainSameElements(array $expected, array $actual, callable $comparisonFunction): void
    {
        Assert::assertEquals(\count($expected), \count($actual));

        self::assertEveryElementOfArrayIsInAnotherArrayTheSameAmountOfTimes($expected, $actual, $comparisonFunction);
        self::assertEveryElementOfArrayIsInAnotherArrayTheSameAmountOfTimes($actual, $expected, $comparisonFunction);
    }

    /**
     * @param array<mixed> $needles
     * @param array<mixed> $haystack
     *
     * @throws InvalidArgumentException
     */
    private static function assertEveryElementOfArrayIsInAnotherArrayTheSameAmountOfTimes(
        array $needles,
        array $haystack,
        callable $comparisonFunction
    ): void {
        Assert::assertLessThanOrEqual(\count($needles), \count($haystack));

        foreach ($needles as $expectedElement) {
            $matchesOfExpectedElementInExpected = \array_filter(
                $needles,
                static fn($element): bool => $comparisonFunction($expectedElement, $element),
            );

            $matchesOfExpectedElementInActual = \array_filter(
                $haystack,
                static fn($element): bool => $comparisonFunction($expectedElement, $element),
            );

            Assert::assertEquals(\count($matchesOfExpectedElementInExpected), \count($matchesOfExpectedElementInActual));
        }
    }
}
trait资产trait
{
/**
*确定两个数组是否具有相同的元素,可能顺序不同。元素比较函数必须作为参数传递。
*
*@param数组应为$
*@param数组$actual
*
*@InvalidArgumentException
*/
公共静态函数AssertArrayScontainsSameeElements(数组$expected,数组$actual,可调用$comparisonFunction):void
{
Assert::assertEquals(\count($预期),\count($实际));
self::AsserteVeryelementToArrayInotherArrayThemeamounttimes($expected,$actual,$comparisonFunction);
self::AsserteVeryelementToArrayInotherArrayThemeamounttimes($actual,$expected,$comparisonFunction);
}
/**
*@param数组$针
*@param数组$haystack
*
*@InvalidArgumentException
*/
私有静态函数AsserteryElementToArrayInotherArrayTheMeasountTimes(
阵列$针,
数组$haystack,
可调用$comparisonFunction
):无效{
Assert::assertLessThanOrEqual(\count($pinees),\count($haystack));
foreach($针作为$expectedElement){
$MatchesOffExpectedElementInExpected=\array\u过滤器(
美元针,
静态fn($element):bool=>$comparisonFunction($expectedElement,$element),
);
$matchesofeexpectedelementinactual=\array\u过滤器(
$haystack,
静态fn($element):bool=>$comparisonFunction($expectedElement,$element),
);
Assert::assertEquals(\count($matchesofeexpectedelementinspected),\count($matchesofeexpectedelementinactual));
}
}
}

我通常在数据库集成测试中使用它来确保返回预期的元素,但我不关心排序。

===
取决于所需的行为。您使用的
=
太多了,应该是
==
=
仅用于记录(因为我的编辑被更改回“用户”),它是“用户”:
['a']==[0]
真的
。好吧,这只是PHP。@DávidHorváth它真的很奇怪,一个好的习惯,它总是使用===@DávidHorváth,松散的比较不仅仅在PHP中是松散的。如果你看JS,你会感到惊讶。在你更好地理解之前不要使用。如果键和值像使用比较一样被移动,就会有问题。但是,假设它们预期100%相同,这是检查深度相等性的最干净、最简单的方法!我想这是最好的解决办法!它可以比较多维数组和关联数组,如果它们以前被排序过的话!如果数组被视为一个集合,那么这是行不通的:它应该按所有数组进行排序
if (array_diff($a,$b) == array_diff($b,$a)) {
  // Equals
}

if (array_diff($a,$b) != array_diff($b,$a)) {
  // Not Equals
}
$a = ['blog', 'company'];
$b = ['company', 'blog'];

(count(array_unique(array_merge($a, $b))) === count($a)) ? 'Equals' : 'Not Equals';
// Equals
function compareIsEqualArray(array $array1,array $array):bool
{

   return (array_diff($array1,$array2)==[] && array_diff($array2,$array1)==[]);

}
$array1 = ['1' => 'XXX', 'second' => [
            'a' => ['test' => '2'],
            'b' => 'test'
        ], 'b' => ['no test']];

        $array2 = [
            '1' => 'XX',
            'second' => [
                'a' => ['test' => '5', 'z' => 5],
                'b' => 'test'
            ],
            'test'
        ];


        function compareArrayValues($arrayOne, $arrayTwo, &$diff = [], $reversed = false)
        {
            foreach ($arrayOne as $key => $val) {
                if (!isset($arrayTwo[$key])) {
                    $diff[$key] = 'MISSING IN ' . ($reversed ? 'FIRST' : 'SECOND');
                } else if (is_array($val) && (json_encode($arrayOne[$key]) !== json_encode($arrayTwo[$key]))) {
                    compareArrayValues($arrayOne[$key], $arrayTwo[$key], $diff[$key], $reversed);
                } else if ($arrayOne[$key] !== $arrayTwo[$key]) {
                    $diff[$key] = 'DIFFERENT';
                }
            }
        }

        $diff = [];
        $diffSecond = [];

        compareArrayValues($array1, $array2, $diff);
        compareArrayValues($array2, $array1, $diffSecond, true);

        print_r($diff);
        print_r($diffSecond);

        print_r(array_merge($diff, $diffSecond));
Array
(
    [0] => DIFFERENT
    [second] => Array
        (
            [a] => Array
                (
                    [test] => DIFFERENT
                    [z] => MISSING IN FIRST
                )

        )

    [b] => MISSING IN SECOND
    [1] => DIFFERENT
    [2] => MISSING IN FIRST
)
trait AssertTrait
{
    /**
     * Determine if two arrays have the same elements, possibly in different orders. Elements comparison function must be passed as argument.
     *
     * @param array<mixed> $expected
     * @param array<mixed> $actual
     *
     * @throws InvalidArgumentException
     */
    public static function assertArraysContainSameElements(array $expected, array $actual, callable $comparisonFunction): void
    {
        Assert::assertEquals(\count($expected), \count($actual));

        self::assertEveryElementOfArrayIsInAnotherArrayTheSameAmountOfTimes($expected, $actual, $comparisonFunction);
        self::assertEveryElementOfArrayIsInAnotherArrayTheSameAmountOfTimes($actual, $expected, $comparisonFunction);
    }

    /**
     * @param array<mixed> $needles
     * @param array<mixed> $haystack
     *
     * @throws InvalidArgumentException
     */
    private static function assertEveryElementOfArrayIsInAnotherArrayTheSameAmountOfTimes(
        array $needles,
        array $haystack,
        callable $comparisonFunction
    ): void {
        Assert::assertLessThanOrEqual(\count($needles), \count($haystack));

        foreach ($needles as $expectedElement) {
            $matchesOfExpectedElementInExpected = \array_filter(
                $needles,
                static fn($element): bool => $comparisonFunction($expectedElement, $element),
            );

            $matchesOfExpectedElementInActual = \array_filter(
                $haystack,
                static fn($element): bool => $comparisonFunction($expectedElement, $element),
            );

            Assert::assertEquals(\count($matchesOfExpectedElementInExpected), \count($matchesOfExpectedElementInActual));
        }
    }
}