0

I have two multidimensional arrays that I want to compare. This is how they look like. I want to get the difference. I tried array diff but it doesn't seem to work. Heres is my code

Array1
(
  [0] => Array
  (
    [name] => john
    [surname] => elvis
    [idnumber] => 01148015
  )
  [1] => Array
  (
    [name] => sammy
    [surname] => dwayne
    [idnumber] => 01148046
  )
)

Array2
(
  [0] => Array
  (
    [name] => john
    [surname] => elvis
    [idnumber] => 01148015
  )
)

$difference = array_diff($Array1, $Array2);
print_r($difference);
Vini.g.fer
  • 11,639
  • 16
  • 61
  • 90
ernys
  • 111
  • 1
  • 7

2 Answers2

1

Use array_intersect() instead:

$result = array_intersect($array1, $array2);
Bhupesh
  • 883
  • 7
  • 16
  • array_intersect gets error...array to string conversion – ernys May 30 '16 at 12:14
  • Try this:"a1","b"=>"b1","c"=>"c1","d"=>"d1"); $a2=array("e"=>"e1","f"=>"f1","a"=>"a1"); $result=array_diff($a1,$a2); echo "Diff:
    "; print_r($result); $result1=array_intersect($a1,$a2); echo "
    InterSect:
    "; print_r($result1); ?>
    – Bhupesh May 30 '16 at 12:24
  • array_map("unserialize", array_intersect($array1, $array2)) – Bhupesh May 30 '16 at 12:30
0

Try this:

You can also see here: http://php.net/manual/en/function.array-diff-assoc.php#111675

array_diff_assoc_recursive($a1, $a2);

function array_diff_assoc_recursive($array1, $array2)
{
    foreach($array1 as $key => $value)
    {
        if(is_array($value))
        {
            if(!isset($array2[$key]))
            {
                $difference[$key] = $value;
            }
            elseif(!is_array($array2[$key]))
            {
                $difference[$key] = $value;
            }
            else
            {
                $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                if($new_diff != FALSE)
                {
                    $difference[$key] = $new_diff;
                }
            }
        }
        elseif(!isset($array2[$key]) || $array2[$key] != $value)
        {
            $difference[$key] = $value;
        }
    }
    return !isset($difference) ? 0 : $difference;
}
Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27