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.
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.
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);
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With