PHP: Merge Two Arrays but Keep Their Keys Intact CodeUnit 03 SEP 2010

Combining two or more arrays whilst keeping their keys intact in PHP is deceptively simple – though not if you assume you need to use a function like array_merge to achieve this!

As you scroll through the various array functions available to you, you will notice that quite a few seem to drop the array keys after they are done, which is pretty useless if all you want to do is basically add two arrays to one another to form one big keyed array.

So how do you do this then?

Simple really. Just literally add them together!

$resultarr = $array1 + $array2;

And just in case you are wondering what the hell is going on, remember that when applied to arrays, the + acts as a union operator.


Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • Thanks for this – I was bashing my head against the wall using array_merge().

  • Guest

    Brilliant!! I love posts like this for the stupider of us wannabe geeks – I too was having headaches with array_merge().

  • Phoenix Kiula

    How do I add two arrays, where the second array basically gets appended to the first? Even in your example, the keys are replaced. As in, the resulting array has only unique keys each. I want all the keys from both arrays to remain…any ideas? 

  • Peter

    It wouldn’t work for me:

    $resultarr = $array1 + $array2;
    // returns Array ( [0] => array1 )

    • Weird, don’t have an answer for you until I get a chance to have a look at this again. Sorry about that.

      • Andrew

        That is exactly as you would expect.
        you could rewrite this:
        $array1=array(0 => “array1”);
        $array2=array(0 => “array2”);

        When we union the two there is a clash of keys for key 0, therefore the first array’s value is given precidence.


        • Ha ha, of course! And now we know. Thanks Andrew!

  • Neo85

     thx this helped me a lot , so simple , me stupid :D

    • Ewrewrew


  • Marsov

    Nailed it! Bravo.