Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging arrays with the same keys

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?

like image 467
kuzey beytar Avatar asked May 04 '11 09:05

kuzey beytar


People also ask

How do you merge arrays?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How do I combine two arrays into a new array?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.


1 Answers

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.

like image 113
Jon Avatar answered Sep 23 '22 18:09

Jon