views:

119

answers:

3

Hey everyone,

I am trying to compare to multidimentional 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?

Thanks for the help!

+2  A: 

There's a user contributed note on the manual page for array_diff_assoc() that seems like it does what you're asking for.

Peter Bailey
This is exactly what I needed. I missed it when I went through the manual, lol!
TheGNUGuy
+1  A: 

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
+3  A: 

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
Creative. I like it. +1
Peter Bailey