Opposite of array_intersect?

PhpArraysArray Intersect

Php Problem Overview


Is there a built-in function to get all members of array 1 which do not exist in array 2?
I know how to do it programatically, only wondering if there is a built-in function that does the same. So please, no code examples.

Php Solutions


Solution 1 - Php

That sounds like a job for array_diff.

> Returns an array containing all the > entries from array1 that are not > present in any of the other arrays.

Solution 2 - Php

array_diff is definitely the obvious choice but it is not technically the opposite of array interesect. Take this example:

$arr1 = array('rabbit','cat','dog');

$arr2 = array('cat','dog','bird');

print_r( array_diff($arr1, $arr2) );

What you want is a result with 'rabbit' and 'bird' in it but what you get is only rabbit because it is looking for what is in the first array but not the second (and not vice versa). to truly get the result you want you must do something like this:

$arr1 = array('rabbit','cat','dog');

$arr2 = array('cat','dog','bird');

$diff1 = array_diff($arr1, $arr2);
$diff2 = array_diff($arr2, $arr1);
print_r( array_merge($diff1, $diff2) );

> Note: This method will only work on arrays with numeric keys.

Solution 3 - Php

$diff = array_diff($array1, $array2);

array_diff()

Solution 4 - Php

Just to clarify as I was looking into this question the answers of @Jon and @Dallas Caley are both correct depending on the domain of your arrays.

If the array against what you are comparing is the full domain of your results then a simple array_diff will suffice as per @Jon answer.

If the array against what you are comparing is NOT the full domain of your results then you should go with the double array_diff as per @Dallas Caley answer.

Solution 5 - Php

I found this docstore.mik.ua/orelly/webprog/pcook/ch04_24.htm quite useful.

You might want a reverse diff, by reversing the order of the arrays in a standard diff.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionItay Moav -MalimovkaView Question on Stackoverflow
Solution 1 - PhpJonView Answer on Stackoverflow
Solution 2 - PhpDallas CaleyView Answer on Stackoverflow
Solution 3 - PhpKingCrunchView Answer on Stackoverflow
Solution 4 - PhpKhel_MVAView Answer on Stackoverflow
Solution 5 - PhpJesseView Answer on Stackoverflow