array_diff() with multidimensional arrays

You can define a custom comparison function using array_udiff().

function udiffCompare($a, $b)
{
    return $a['ITEM'] - $b['ITEM'];
}

$arrdiff = array_udiff($arr2, $arr1, 'udiffCompare');
print_r($arrdiff);

Output:

Array
(
    [3] => Array
        (
            [ITEM] => 4
        )
)

This uses and preserves the arrays' existing structure, which I assume you want.


I would probably iterate through the original arrays and make them 1-dimensional... something like

foreach($array1 as $aV){
    $aTmp1[] = $aV['ITEM'];
}

foreach($array2 as $aV){
    $aTmp2[] = $aV['ITEM'];
}

$new_array = array_diff($aTmp1,$aTmp2);

Another fun approach with a json_encode trick (can be usefull if you need to "raw" compare some complex values in the first level array) :

// Compare all values by a json_encode
$diff = array_diff(array_map('json_encode', $array1), array_map('json_encode', $array2));

// Json decode the result
$diff = array_map('json_decode', $diff);

Tags:

Php

Arrays