phparraysmultidimensional-arrayfilterarray-difference

Filter the rows of a 2d array by another 2d array and comparing only a single column of values


Array 1 ($allmodels)
Array ( [0] => Array ( [id] => 6 ) 
        [1] => Array ( [id] => 7 ) 
        [2] => Array ( [id] => 8 ) ) 

Array 2 ($existmodels)
Array ( [0] => Array ( [id] => 6 ) 
        [1] => Array ( [id] => 4 ) 
        [2] => Array ( [id] => 7 ) 
        [3] => Array ( [id] => 5 ) )

What I want as output array is(get the remaining models using $allmodels - $existmodels )

Array ( [0] => Array ( [id] => 8 ))

I tried

array_diff($allmodels,$existmodels); AND array_diff_assoc($allmodels,$existmodels); which both result

Array ( )

Can anyone tell me how can I get it done ?


Solution

  • Note of array_diff:

    Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

    The string representation of array is both Array, so this is the reason why you get empty array as result.

    You could use array_filter instead.

    var_dump(array_filter($allmodels, function ($var) use ($existmodels) {
      return !in_array($var, $existmodels);
    }));