32

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Ben Everard
  • 13,652
  • 14
  • 67
  • 96

2 Answers2

69

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);
Matt
  • 74,352
  • 26
  • 153
  • 180
Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
0

Uses of array_dif in php://It removes values from first array if that are exist in second array.

 $foo = array(1, 5, 9, 14, 23, 31, 45);
 $bar = array(14, 31, 36);
 $data = array_diff($foo,$bar);
 print_r($data);
Kabir Hossain
  • 2,865
  • 1
  • 28
  • 34