-1

I am trying to compare to multidimensional arrays, but I can't just use array_diff_assoc(). The arrays I am trying to compare are both associative arrays, and they are both sorted so the keys are in the same order. For the most part the arrays are identical in structure. I can't seem to figure out how to compare the elements that store arrays, I can compare the elements that hold one value just fine does anyone know what I can do?

Cœur
  • 37,241
  • 25
  • 195
  • 267
cskwrd
  • 2,803
  • 8
  • 38
  • 51
  • So.... `but I can't just use array_diff_assoc()`, and then you accept an answer that advises the use of `array_diff_assoc()`. Please forgive me for voting to close as Unclear. – mickmackusa Feb 22 '22 at 22:54
  • A better [mcve] here: https://stackoverflow.com/questions/4742405/array-diff-to-compare-two-associative-arrays – mickmackusa Feb 22 '22 at 23:12
  • There's a [user contributed note](http://us2.php.net/array_diff_assoc#73972) on the manual page for [array_diff_assoc()](http://us2.php.net/array_diff_assoc) that seems like it does what you're asking for. – Peter Bailey Jul 15 '09 at 18:33

2 Answers2

3

If your trying to just see if they are different (and not what specifically is different) you could try something like:

 return serialize($array1) == seralize($array2);

That would give you a yea or neah on the equality of the two arrays.

null
  • 7,432
  • 4
  • 26
  • 28
1

It's not clear whether you want to see if they're equal, or actually want an output of what the differences are.

If it's the former then you could do it the proper way, with a recursive function:

$array1 = array('a' => 1, 'b' => 2, 'c' => array('ca' => 1, 'cb' => array('foo')));
$array2 = array('a' => 1, 'b' => 2, 'c' => array('ca' => 1, 'cb' => array('bar')));

var_dump(arrayEqual($array1, $array2));

function arrayEqual($a1, $a2)
{
    if (count(array_diff($a1, $a2)))
        return false;

    foreach ($a1 as $k => $v)
    {
        if (is_array($v) && !arrayEqual($a1[$k], $a2[$k]))
            return false;
    }

    return true;
}

Or use a complete hack like this:

if (serialize($array1) == serialize($array2))
Greg
  • 316,276
  • 54
  • 369
  • 333