Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...