Merging arrays with the same keys

beytarovski picture beytarovski · May 4, 2011 · Viewed 142.5k times · Source

In a piece of software, I merge two arrays with array_merge function. But I need to add the same array (with the same keys, of course) to an existing array.

The problem:

 $A = array('a' => 1, 'b' => 2, 'c' => 3);
 $B = array('c' => 4, 'd'=> 5);

 array_merge($A, $B);

 // result
 [a] => 1 [b] => 2 [c] => 4 [d] => 5

As you see, 'c' => 3 is missed.

So how can I merge all of them with the same keys?

Answer

Jon picture Jon · May 4, 2011

You need to use array_merge_recursive instead of array_merge. Of course there can only be one key equal to 'c' in the array, but the associated value will be an array containing both 3 and 4.