dino dino - 1 year ago 85
PHP Question

Merging arrays with the same keys

In a piece of software, I merge two arrays with

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?

Jon Jon
Answer Source

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.

See it in action.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download