PHP - Check if two arrays are equal

PhpArrays

Php Problem Overview


I'd like to check if two arrays are equal. I mean: same size, same index, same values. How can I do that?

Using !== as suggested by a user, I expect that the following would print enter if at least one element in the array(s) are different, but in fact it does not.

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

    echo "enter";
}

Php Solutions


Solution 1 - Php

$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.

See Array Operators.

EDIT

The inequality operator is != while the non-identity operator is !== to match the equality operator == and the identity operator ===.

Solution 2 - Php

According to this page.

NOTE: The accepted answer works for associative arrays, but it will not work as expected with indexed arrays (explained below). If you want to compare either of them, then use this solution. Also, this function may not works with multidimensional arrays (due to the nature of array_diff function).

Testing two indexed arrays, which elements are in different order, using $a == $b or $a === $b fails, for example:

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

That is because the above means:

array(0 => "x", 1 => "y") vs. array(0 => "y", 1 => "x").

To solve that issue, use:

<?php
function array_equal($a, $b) {
    return (
         is_array($a) 
         && is_array($b) 
         && count($a) == count($b) 
         && array_diff($a, $b) === array_diff($b, $a)
    );
}
?>

Comparing array sizes was added (suggested by super_ton) as it may improve speed.

Solution 3 - Php

Try serialize. This will check nested subarrays as well.

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

Solution 4 - Php

Short solution that works even with arrays which keys are given in different order:

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

Solution 5 - Php

Compare them as other values:

if($array_a == $array_b) {
  //they are the same
}

You can read about all array operators here: http://php.net/manual/en/language.operators.array.php Note for example that === also checks that the types and order of the elements in the arrays are the same.

Solution 6 - Php

function compareIsEqualArray(array $array1,array $array2):bool
{

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

}

Solution 7 - Php

!=== will not work because it's a syntax error. The correct way is !== (not three "equal to" symbols)

Solution 8 - Php

if (array_diff($a,$b) == array_diff($b,$a)) {
  // Equals
}

if (array_diff($a,$b) != array_diff($b,$a)) {
  // Not Equals
}

From my pov it's better to use array_diff than array_intersect because with checks of this nature the differences returned commonly are less than the similarities, this way the bool conversion is less memory hungry.

Edit Note that this solution is for plain arrays and complements the == and === one posted above that is only valid for dictionaries.

Solution 9 - Php

Another method for checking equality regardless of value order works by using http://php.net/manual/en/function.array-intersect.php, like so:

$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';
}

Here's a version that works also with multidimensional arrays using http://php.net/manual/en/function.array-uintersect.php:

$array1 = array(
    array(5, 2),
	array(3, 6),
	array(2, 9, 4)
);
$array2 = array(
	array(3, 6),
	array(2, 9, 4),
	array(5, 2)
);

if($array1 === array_uintersect($array1, $array2, 'compare') && $array2 === array_uintersect($array2, $array1, 'compare')) {
    echo 'Equal';
} else {
    echo 'Not equal';
}

function compare($v1, $v2) {
	if ($v1===$v2) {
		return 0;
	}
	if ($v1 > $v2) return 1;
	return -1;
}

Solution 10 - Php

array_diff — Computes the difference of arrays

http://php.net/manual/en/function.array-diff.php

> array array_diff ( array $array1 , array $array2 [, array $... ] ) > > Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

Solution 11 - Php

One way: (implementing 'considered equal' for https://www.rfc-editor.org/rfc/rfc6902#section-4.6)

This way allows associative arrays whose members are ordered differently - e.g. they'd be considered equal in every language but php :)

// recursive ksort
function rksort($a) {
  if (!is_array($a)) {
    return $a;
  }
  foreach (array_keys($a) as $key) {
    $a[$key] = ksort($a[$key]);
  }
  // SORT_STRING seems required, as otherwise
  // numeric indices (e.g. "0") aren't sorted.
  ksort($a, SORT_STRING);
  return $a;
}


// Per https://www.rfc-editor.org/rfc/rfc6902#section-4.6
function considered_equal($a1, $a2) {
  return json_encode(rksort($a1)) === json_encode(rksort($a2));
}

Solution 12 - Php

Syntax problem on your arrays

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

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

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

var_dump($diff); 

Solution 13 - Php

Here is the example how to compare to arrays and get what is different between them.

$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));

Result:

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

        )

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

Solution 14 - Php

If you want to check non associative arrays, here is the solution:

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

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

Solution 15 - Php

The following solution works with custom equality functions that you can pass as a callback. Note that it doesn't check arrays order.

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));
        }
    }
}

I usually use it in database integrations tests when I want to ensure that the expected elements are returned but I don't care about the sorting.

Solution 16 - Php

The proper way to compare whether two arrays are equal is to use strict equality (===), which compares recursively. Existing answers are unable to recursively sort an arbitrary array (array of arbitrary depth and order, containing a mixture of sequential and associative arrays) and hence cannot handle comparisons of arbitrary arrays. Sequential arrays are associative arrays with a sequential key (0,1,2,3...) whereas associative arrays do not have a sequential key.

To sort these arbitrary arrays, we have to:

  1. Traverse downwards towards leaf nodes with no more sub-arrays
  2. Sort sequential arrays by serializing then sorting them (to remove the need of having to use custom comparators)
  3. Sort associative arrays by key

The following code implements the solution described above. Improvements to the code are welcome.

function recur_sort( &$array ) {
	foreach ( $array as &$value ) {
	   if ( is_array( $value ) ) recur_sort( $value );
	}

	if ( is_sequential_array( $array ) ) {
		$array = array_map( function( $el ) { return json_encode( $el ); }, $array  );
		sort( $array, SORT_STRING );
		$array = array_map( function( $el ) { return json_decode( $el, true ); }, $array  );
		return;
	} else {
		return ksort( $array );
	}
}

function is_sequential_array(Array &$a) {
    $n = count($a);
    for($i=0; $i<$n; $i++) {
        if(!array_key_exists($i, $a)) {
            return false;
        }
    }
    return true;
}

Example (in PHPUnit):

//A stricter and recursive assertEqualsCanonicalizing
public function assertSameCanonicalizing( $expected, $actual ) {
    recur_sort( $expected );
    recur_sort( $actual );
    $this->assertSame( $expected, $actual );
}

Solution 17 - Php

If you want to check that your arrays have the strictly equal (===) associations of keys and values, you can use the following function:

function array_eq($a, $b) {
    // If the objects are not arrays or differ in their size, they cannot be equal
    if (!is_array($a) || !is_array($b) || count($a) !== count($b)) {
        return false;
    }
    // If the arrays of keys are not strictly equal (after sorting),
    // the original arrays are not strictly equal either
    $a_keys = array_keys($a);
    $b_keys = array_keys($b);
    array_multisort($a_keys);
    array_multisort($b_keys);
    if ($a_keys !== $b_keys) {
        return false;
    }
    // Comparing values
    foreach ($a_keys as $key) {
        $a_value = $a[$key];
        $b_value = $b[$key];
        // Either the objects are strictly equal or they are arrays
        // which are equal according to our definition. Otherwise they
        // are different.
        if ($a_value !== $b_value && !array_eq($a_value, $b_value)) {
            return false;
        }
    }
    return true;
}

Solution 18 - Php

Use php function array_diff(array1, array2);

It will return a the difference between arrays. If its empty then they're equal.

example:

$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' ) 

Example 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; 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarkzzzView Question on Stackoverflow
Solution 1 - PhpStefan GehrigView Answer on Stackoverflow
Solution 2 - PhplepeView Answer on Stackoverflow
Solution 3 - PhpIggiView Answer on Stackoverflow
Solution 4 - PhpSamuel VicentView Answer on Stackoverflow
Solution 5 - PhpEmil VikströmView Answer on Stackoverflow
Solution 6 - Phpdılo sürücüView Answer on Stackoverflow
Solution 7 - PhpSodhi saabView Answer on Stackoverflow
Solution 8 - PhpMarcos Fernandez RamosView Answer on Stackoverflow
Solution 9 - PhpwhitebrowView Answer on Stackoverflow
Solution 10 - PhpScherbius.comView Answer on Stackoverflow
Solution 11 - PhpMike McCabeView Answer on Stackoverflow
Solution 12 - PhpYEFFOU WAGOUM THIERRY HENRIView Answer on Stackoverflow
Solution 13 - PhpMarko ŠutijaView Answer on Stackoverflow
Solution 14 - PhpSanto BoldizarView Answer on Stackoverflow
Solution 15 - PhpLorenzo Franco RanucciView Answer on Stackoverflow
Solution 16 - PhpToh NicView Answer on Stackoverflow
Solution 17 - PhpRichard BlažekView Answer on Stackoverflow
Solution 18 - PhpWolfgang LeonView Answer on Stackoverflow