marcosh
marcosh

Reputation: 9008

php - check if two arrays have the same values

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

Upvotes: 2

Views: 2510

Answers (1)

Brilliand
Brilliand

Reputation: 13714

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.

Upvotes: 2

Related Questions