phparraysassociative-arrayarray-merge

Merge two associative arrays without losing elements during key collisions


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

  • Try with array_merge_recursive

    $A = [
      'a' => 1,
      'b' => 2,
      'c' => 3,
    ];
    
    $B = [
      '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
    )