Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of array_intersect?

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.

like image 556
Itay Moav -Malimovka Avatar asked Apr 07 '11 13:04

Itay Moav -Malimovka


People also ask

What is Array_intersect?

The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

How can I get unique values from two arrays in PHP?

The array_diff() (manual) function can be used to find the difference between two arrays: $array1 = array(10, 20, 40, 80); $array2 = array(10, 20, 100, 200); $diff = array_diff($array1, $array2); // $diff = array(40, 80, 100, 200);

How can I find the difference between two arrays in PHP?

The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.

How do I check if two arrays have the same element in PHP?

Now, to check whether two arrays are equal or not, an iteration can be done over the arrays and check whether for each index the value associated with the index in both the arrays is the same or not. PHP has an inbuilt array operator( === ) to check the same but here the order of array elements is not important.


2 Answers

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.

like image 169
Jon Avatar answered Oct 01 '22 12:10

Jon


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.

like image 44
Dallas Caley Avatar answered Oct 01 '22 11:10

Dallas Caley