29

Lets say I have the following two PHP arrays that contain integers:

$foo = array(1, 5, 9, 14, 23, 31, 45);
$bar = array(14, 31, 36);

I want to remove the items in $foo where the same value exists in $bar

So the result of the process would create a $filteredFoo array that contains:

1, 5, 9, 23, 45

Having looked through the docs on php.net there doesn't seem to be an existing function to perform this kind of action. So is my only option to use foreach and iterate through $foo checking values $bar on each iteration?

Dharman
  • 30,962
  • 25
  • 85
  • 135
MrEyes
  • 13,059
  • 10
  • 48
  • 68

1 Answers1

56

You can use array_diff():

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

$filteredFoo = array_diff($foo, $bar);
Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185