5

Arguments are like this:

function foo(arr1, arr2, arr3, arr4 ...)

and the function should return a array of all elements from arr2, arr3, arr4 ... that don't exist in arr1.

Is there a built in function for this? Or do I need to make it myself with foreach and stuff? :)

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Alex
  • 66,732
  • 177
  • 439
  • 641

3 Answers3

10

There is no built-in function that does exactly what you are asking for. array_diff() is close, but not quite. So you'll have to roll your own nice neat function or else do something ugly like this:

array_diff( array_unique(
                array_merge(
                    array_values($arr2), 
                    array_values($arr3), 
                    array_values($arr4)
                )),
                $arr1 
           );

You can remove the call to array_unique() if you want values that appear multiple times in the arrays to also be represented multiple times in your result.

You can remove the calls to array_values() if your keys in your arrays are all numeric or if you are certain that there are no non-numeric keys that appear in more than one of the arrays being merged.

So, in those ideal circumstances, it can be simplified to:

array_diff( array_merge( $arr2, $arr3, $arr4 ), $arr1 );
Trott
  • 66,479
  • 23
  • 173
  • 212
5

You can do this with array_diff, but you'll have to turn things around a bit.

$result = array_diff (array_merge ($arr2, $arr3, $arr4), $arr1);

EDIT: Trott's answer covers a load of edge cases that mine doesn't. That's probably the best solution you're going to get.

GordonM
  • 31,179
  • 15
  • 87
  • 129
1

That is what you're looking for :

http://www.php.net/manual/en/function.array-diff.php

Imad Moqaddem
  • 1,453
  • 9
  • 11