Jump to content

Checking one array to see if it's in another


galvin

Recommended Posts

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!

 

 

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.