33

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.

2 Answers 2

70

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);
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.