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!

 

 

Link to comment
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.