galvin Posted July 30, 2012 Share Posted July 30, 2012 If I have two arrays like this... Array 1: Array ( [0] => 14 [1] => 23 [2] => 267 [3] => 303 ) Array 2: Array ( [0] => 6 [1] => 88 [2] => 267 [3] => 311 ) What is most efficient way to check if any values from Array 2 are in Array 1, and if so, remove them. So using the example above, it would need to find that 267 is in both arrays and remove 267 from Array 2 (but leave it in Array 1). Thanks! Link to comment https://forums.phpfreaks.com/topic/266432-checking-one-array-to-see-if-its-in-another/ Share on other sites More sharing options...
thara Posted July 30, 2012 Share Posted July 30, 2012 You can just use array_diff or array_intersect function. See also array_unique. If you concatenate the two arrays, it will then yank all duplicates. Link to comment https://forums.phpfreaks.com/topic/266432-checking-one-array-to-see-if-its-in-another/#findComment-1365332 Share on other sites More sharing options...
Psycho Posted July 30, 2012 Share Posted July 30, 2012 To add a little more clarity. Use array_intersect() to find the duplicates. Then use array_diff() on those dupes and array2 to get array2 without the dupes. A long hand example: $dupes = array_intersect($array1, $array2); $array2 = array_diff($array2, $dupes); A single line example: $array2 = array_diff($array2, array_intersect($array1, $array2)); Or, create a function passing array2 by reference: //Remove duplicate values from 2nd array function removeDupes($arr1, &$arr2) { $dupes = array_intersect($arr1, $arr2); $arr2 = array_diff($arr2, $dupes); } //Usage removeDupes($array1, $array2); //After calling the function $array2 will be reset without the dupes Link to comment https://forums.phpfreaks.com/topic/266432-checking-one-array-to-see-if-its-in-another/#findComment-1365341 Share on other sites More sharing options...
galvin Posted July 30, 2012 Author Share Posted July 30, 2012 Great, thank you both very much! Link to comment https://forums.phpfreaks.com/topic/266432-checking-one-array-to-see-if-its-in-another/#findComment-1365438 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.