PHP: How to array_merge Without Losing Numeric Keys

PHP function array_merge is nice in that you can easily merge one (or more) arrays into a single array with a single call of the function. The keys are retained, but only if they’re not numeric keys(!).

E.g.

Perhaps this is the behavior you want. But what if you want to retain the original numeric keys?

Most PHP developers tend to create a custom (unnecessary) array_merge function that applies simple logic in order to retain numeric keys during the merge, but the solution is quite simple:

 

That’s it. By simply using the add operator you effectively get the array_merge result except you retain the numeric keys.

Leave a Reply

Your email address will not be published. Required fields are marked *