Looping through an array to remove elements found in another array

Is it possible to use a foreach, or something similar, to loop through an array of keywords and delete the keyword if it exists in another array? I’ve been researching online and can’t find an example of what I’m trying to do. There are many foreach examples, but not where they delete elements out of the array if they exist in another array.


Have you tried array_diff ?

Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

Yes, I’m actually using that one. Let me describe the situation better.

I made an array of the title of my article. Then I made an array of the keywords of my article. Then I used array_diff to see if there were some elements in the keywords array that also exist in the title array. If so, those words are stored in a third duplicates array.

So now I just need to use the duplicate words array and loop through the keywords array, unsetting any matches. Does this make more sense?


You could, but you do not need to.
array_diff will return an array with those found in the other removed.

$array_one = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten');
$array_two = array('two', 'three', 'five', 'seven');
echo "<br />";
$array_one = array_diff( $array_one, $array_two );


Array ( [0] => zero [1] => one [2] => two [3] => three [4] => four [5] => five [6] => six [7] => seven [8] => eight [9] => nine [10] => ten )
Array ( [0] => zero [1] => one [4] => four [6] => six [8] => eight [9] => nine [10] => ten )

That will work perfectly! I didn’t think to assign the difference of $array_one and $array_two to $array_one.

Thanks Mittineague!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.