array_intersect throws errors when arrays have sub-arrays

Force Flow picture Force Flow · Sep 25, 2013 · Viewed 8k times · Source

I'm trying to use array_intersect to compare two arrays of arrays.

$start[]=array(
        'id'=>1,
        'name'=>'Up',
        'action'=>'up'
);
$start[]=array(
        'id'=>3,
        'name'=>'Down',
        'action'=>'down'
);
$start[]=array(
        'id'=>5,
        'name'=>'Left',
        'action'=>'left'
);




$end[]=array(
        'id'=>1,
        'name'=>'Up',
        'action'=>'up'
);
$end[]=array(
        'id'=>9,
        'name'=>'Up',
        'action'=>'up'
);

$result=array_intersect($start,$end);

However, I always get the notice message:

Notice: Array to string conversion in testfile.php on line xyz

And the comparison doesn't actually occur.

What is the best way to compare the two arrays without reinventing the wheel or arriving at something overly complex?

Answer

SamA picture SamA · Sep 25, 2013

The array_diff and array_intersect convert each element in the primary array in to a string for comparison. If you would like a different comparison, then you could use the callback method with the following built-in functions:

array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

I found these by searching PHP.net for the function array_diff and followed the related function links. Its a great way to see alternatives for doing something.