Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing items from an array if they exist in another array [duplicate]

Tags:

arrays

php

Possible Duplicate:
Remove item from array if it exists in a 'disallowed words' array

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?

like image 570
MrEyes Avatar asked Dec 03 '10 15:12

MrEyes


1 Answers

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); 
like image 159
Tatu Ulmanen Avatar answered Sep 21 '22 15:09

Tatu Ulmanen