2

I would like to know which is the fastest way to check that two (possibly multidimensional) arrays contain the same values.

In other terms I would like to know if the (unordered) set of values of the first array is equal to the set of values of the second array

UPDATE:

1) cannot use == or ===. They check also for key equality.

2) cannot use array_diff. It doesn't work with multidimensional arrays

marcosh
  • 8,780
  • 5
  • 44
  • 74
  • 1
    http://php.net/array_diff. If the diff is empty, then they've got the same contents. – Marc B May 23 '14 at 16:13
  • http://uk3.php.net/array_diff – Ali Gajani May 23 '14 at 16:13
  • @Alaeddine that post asks to have also the same indices... I want to avoid that – marcosh May 23 '14 at 16:15
  • @MarcB to my knowledge array_diff doesn't work nice with multidimensional arrays – marcosh May 23 '14 at 16:16
  • 1
    I just realized my answer still doesn't do exactly what this question is asking for. You might be better off flattening the array (http://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array) and then using array_diff. – Brilliand Aug 18 '14 at 16:09

1 Answers1

2

There's no simple way to do this for a nested array; you'll have to write your own recursive function. It looks like array_udiff isn't really suitable, either (due to requiring greater-than/less-than information from the comparison function);

This should do the trick:

function recursive_sort_array($a) {
    if(!is_array($a))
        return $a;
    $a = array_map('recursive_sort_array', $a);
    sort($a);
    return array_values($a);
}

function arrays_different($a, $b) {
    return recursive_sort_array($a) === recursive_sort_array($b);
}

What it does: The first function (recursive_sort_array) recursively sorts an array and returns only the values, tied to numeric indexes. Any arrays that have the same values (recursively) will be equal after this operation, and can then be compared with one of the equality operators.

Brilliand
  • 13,404
  • 6
  • 46
  • 58
  • your solution looks good, but doesn't work if an element of an array is an object. Sort doesn't know how to handle it – marcosh May 23 '14 at 18:43
  • @marcosh Comparing objects in PHP is a complicated problem in its own right, and I consider it outside the scope of this question. However, you should be able to extend this to handle arrays of objects by replacing the `sort` with a `usort` that can handle the objects you need to work with. You may also need to use loose comparison (`==`). – Brilliand May 23 '14 at 20:17