Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

I have an array:

Array (     [0] => tom     [1] => and     [2] => jerry ) 

And I also have a disallowed words array:

Array (     [0] => and     [1] => foo     [2] => bar ) 

What I need to do is remove any item in the first array that also appears in the second array, in this instance for example, key 1 would need to be removed, as 'and' is in the disallowed words array.

Now I currently have this code, which does a foreach on the disallowed words and then uses array_search to find any matches:

$arr=array('tom','and','jerry'); $disallowed_words=array('and','or','if'); foreach($disallowed_words as $key => $value) {     $arr_key=array_search($value,$array);     if($arr_key!='') {         unset($search_terms[$arr_key]);     } } 

Now I know this code sucks, what I want to know is if there is a more efficient method of removing and item from an array where it exists in another array, especially if it negates using a foreach.

Many thanks, Ben

like image 275
Ben Everard Avatar asked Nov 13 '09 11:11

Ben Everard


1 Answers

You want array_diff.

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

So you want something like:

$good = array_diff($arr, $disallowed_words); 
like image 164
Dominic Rodger Avatar answered Oct 07 '22 10:10

Dominic Rodger