How to pick what array_intersect function to use in PHP?
So you want to do an intersect, but not sure which PHP function to use? There are around 8 variations on the array
intersection function built into PHP. Here is a guide for helping your pick which one to use!
The main array intersect functions in PHP
The basic idea of all of them is that it will return an array of all values from the first array that are also in the
The differences between them are based on the following:
- If the user provides the compare function (
- If it will compare keys (assoc), values, or both
This is the main one, I guess!
This will return an array with all values from $array1 that are present in all the others. It just compares the
values, ignoring the keys
Same as above, but it checks both values and keys
It checks the keys (via user supplied function) and values. The values are checked by normal comparison, but they keys are checked by a user
Returns array of everything from the first array which have keys in the other arrays.
Same as above, but the comparison function for the keys is provided by the user.
Same as array_intersect() - but the user provides the comparison function for comparing the values
Same as array_uintersect() (above), but the user provided function checks the keys
And in this function it is the two above combined. The user provides 2 comparison functions (one for keys, one for values), and it will check
against both of those.
I've been coding professionally for years in PHP, and I still have to double check which one to use every time...