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?
Solution 1:
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
.
Solution 2:
Try with array_merge_recursive
$A = array('a' => 1, 'b' => 2, 'c' => 3);
$B = array('c' => 4, 'd'=> 5);
$c = array_merge_recursive($A,$B);
echo "<pre>";
print_r($c);
echo "</pre>";
will return
Array
(
[a] => 1
[b] => 2
[c] => Array
(
[0] => 3
[1] => 4
)
[d] => 5
)