PHP - Check if two arrays are equal PHP - Check if two arrays are equal arrays arrays

PHP - Check if two arrays are equal


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


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:

<?phpfunction 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.


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