The array_intersect function will return an array of values that exist in all arrays that were passed to this function.
Array keys are preserved. Indexes from the original arrays are not.
array_intersect only check the values of the arrays. array_intersect_assoc function will return intersection of arrays with keys.
array_intersect_key function only check the intersection of keys. It will returns keys exist in all arrays.
Changing a multidimensional array to associative array
If you have a multidimensional array like this:
And you want to change it to an associative array like this:
You can use this code:
Or, you can skip setting $associativeArrayKeys and $associativeArrayValues and use this simple one liner:
Combining two arrays (keys from one, values from another)
The following example shows how to merge two arrays into one associative array, where the key values will be the items of the first array, and the values will be from the second:
Merge or concatenate arrays
Note that array_merge will change numeric indexes, but overwrite string indexes
array_merge overwrites the values of the first array with the values of the second array, if it cannot renumber the index.
You can use the + operator to merge two arrays in a way that the values of the first array never get overwritten, but it does not renumber numeric indexes, so you lose values of arrays that have an index that is also used in the first array.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0