Search code examples
phparraysarray-merge

Array merge on the go


I often start to define an array, and then figure out I need to break it up in two or more pieces. I would then start with $array('key' => 'value') for my first values and then having to rewrite the code for the other parts of the array like this: $array['key'] = 'value'. But that's a hassle.

So I tried the following, that seems to work:

$my_true_love_sent_me_for_christmas = array(
    'First day'     =>  'A Partridge in a Pear Tree',
    'Second day'    =>  '2 Turtle Doves',
    'Third day'     =>  '3 French Hens',
    'Fourth day'    =>  '4 Calling Birds',
);

breathe(); // breathe, and then I want to continue my array where I left it.

$my_true_love_sent_me_for_christmas = array_merge($my_true_love_sent_me_for_christmas, array(
    'Fifth day'     =>  '5 Golden Rings',
    'Sixth day'     =>  '6 Geese a Laying',
    'Seventh day'   =>  '7 Swans a Swimming',
    'Eighth day'    =>  '8 Maids a Milking',
));

breathe(); // breathe, and then I want to continue my array where I left it.

$my_true_love_sent_me_for_christmas = array_merge($my_true_love_sent_me_for_christmas, array(
    'Ninth day'     =>  '9 Ladies Dancing',
    'Tenth day'     =>  '10 Lords a Leaping',
    'Eleventh day'  =>  '11 Pipers Piping',
    'Twelfth day'   =>  '12 Drummers Drumming',
));

Is there a better/cleaner/faster way of doing merging an array on the go?


Solution

  • The simplest way seems to be:

    $foo = [
        'First day'  => 'A Partridge in a Pear Tree',
        'Second day' => '2 Turtle Doves',
        'Third day'  => '3 French Hens',
        'Fourth day' => '4 Calling Birds',
    ];
    
    $foo += [
        'Fifth day'   => '5 Golden Rings',
        'Sixth day'   => '6 Geese a Laying',
        'Seventh day' => '7 Swans a Swimming',
        'Eighth day'  => '8 Maids a Milking',
    ];
    
    $foo += [
        'Ninth day'    => '9 Ladies Dancing',
        'Tenth day'    => '10 Lords a Leaping',
        'Eleventh day' => '11 Pipers Piping',
        'Twelfth day'  => '12 Drummers Drumming',
    ];
    
    print_r($foo);
    

    Reference: https://php.net/manual/language.operators.array.php

    The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.