search

Home  >  Q&A  >  body text

How to merge arrays and keep keys?

I have two arrays:

$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456);

I want to merge them and preserve keys and order instead of re-indexing! !

How did it become like this?

Array
(
    [a] => new value
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
    [123] => 456
)

I tried array_merge() but it doesn't preserve the keys:

print_r(array_merge($array1, $array2));

Array
(
    [a] => 'new value'
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
    [0] => 456
)

I tried using the union operator but it doesn't overwrite the element:

print_r($array1 + $array2);

Array
(
    [a] => 1   <-- not overwriting
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
    [123] => 456
)

I tried swapping places, but it was in the wrong order, not what I needed:

print_r($array2 + $array1);

Array
(
    [d] => 4
    [e] => 5
    [f] => 6
    [a] => new value 
    [123] => 456
    [b] => 2
    [c] => 3
)

I don't want to use loops, is there a way to get high performance?

P粉081360775P粉081360775408 days ago570

reply all(2)I'll reply

  • P粉593536104

    P粉5935361042023-10-18 09:51:37

    Suppose we have 3 arrays as shown below.

    $a = array(0=>['label'=>'Monday','is_open'=>1],1=>['label'=>'Tuesday','is_open'=>0]);
    
    $b = array(0=>['open_time'=>'10:00'],1=>['open_time'=>'12:00']); 
    
    $c = array(0=>['close_time'=>'18:00'],1=>['close_time'=>'22:00']);

    Now if you want to merge all these arrays and want the final array to contain all the array data under keys 0 in 0 and 1 in 1 and so on.

    Then you need to use the array_replace_recursive PHP function as follows.

    $final_arr = array_replace_recursive($a, $b , $c);

    The results are as follows.

    Array
    (
        [0] => Array
            (
                [label] => Monday
                [is_open] => 1
                [open_time] => 10:00
                [close_time] => 18:00
            )
    
        [1] => Array
            (
                [label] => Tuesday
                [is_open] => 0
                [open_time] => 12:00
                [close_time] => 22:00
            )
    
    )

    Hope the above solution can best suit your requirements! !

    reply
    0
  • P粉729436537

    P粉7294365372023-10-18 09:45:00

    You are looking forarray_replace():

    $array1 = array('a' => 1, 'b' => 2, 'c' => 3);
    $array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456);
    print_r(array_replace($array1, $array2));

    Available since PHP 5.3.

    renew

    You can also use the union array operator ; it works on older versions and may actually be faster too:

    print_r($array2 + $array1);

    reply
    0
  • Cancelreply