PHP: Built-in function to check whether two Array values are equal ( Ignoring the order)

array_diff looks like an option:

function array_equal($a1, $a2) {
  return !array_diff($a1, $a2) && !array_diff($a2, $a1);
}

or as an oneliner in your code:

if(!array_diff($a1, $a2) && !array_diff($a2, $a1)) doSomething();

The best solution is to sort both array and then compare them:

$a = array('4','5','2');
$b = array('2','4','5');
sort($a);
sort($b);
var_dump($a === $b);

As a function:

function array_equal($a, $b, $strict=false) {
    if (count($a) !== count($b)) {
        return false;
    }
    sort($a);
    sort($b);
    return ($strict && $a === $b) || $a == $b;
}

Here’s another algorithm looking for each element of A if it’s in B:

function array_equal($a, $b, $strict=false) {
    if (count($a) !== count($b)) {
        return false;
    }
    foreach ($a as $val) {
        $key = array_search($val, $b, $strict);
        if ($key === false) {
            return false;
        }
        unset($b[$key]);
    }
    return true;
}

But that has a complexity of O(n^2). So you better use the sorting method.


The array_diff() method above won't work.

php.net's manual says that array_diff() does this:

"Returns an array containing all the entries from array1 that are not present in any of the other arrays."

So the actual array_diff() method would be:

function array_equal($array1, $array2)
{
   $diff1 = array_diff($array1, $array2);
   $diff2 = array_diff($array2, $array1);

   return
   (
      (count($diff1) === 0) &&
      (count($diff2) === 0)
   );
}

However I go with the sort method :D

Tags:

Php

Arrays