Skip to content
Advertisement

PHP – Merge Two Associative Arrays where values match

I have two arrays that need to be merged. I can loop through each array and merge manually. But, Is there a built in function to do this?

Array 1:

JavaScript

Array 2:

JavaScript

Expected Output array is:

JavaScript

I have added only a sample from the array. Array is huge. Is there any PHP functions like array_merge() or array_map() that we can use instead of manual for loops and iterators?

Advertisement

Answer

Older & wiser: I’ve scrubbed my answer from years earlier because I no longer recommend the techniques. It will be most succinct and efficient to merge the arrays, feed them to a foreach() loop, then “unite” (+ is used as an array union operator) data in related rows.

The null coalescing operator (??) is used to ensure that there is always something to “unite” with.

Code: (Demo)

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement