Merging arrays in PHP

Merging arrays in PHP - logoA short story about merging arrays in PHP. When merging two arrays you’ll probably look at array_merge first. These two sentences in the docs say the following:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

But what if you want to keep the numeric keys? You need the + operator.

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.

So there are two functions, doing the same trick but with a slight difference. Next to numeric key preservation there is another difference: the order of the arguments. When using array_merge the values of the array passed in last will win in the case of a collision, with the + operator the values of the left array wins. Thanks PHP!

Alternative to merging arrays in PHP

To end with a positive note, you should look at the symfony/options-resolver component if you have this kind of problem. It solves a lot of use cases where you’re normally use an array_merge. It gives you more control about the allowed values, and gives you exceptions if a required option isn’t present.

If you want to try it out, do so using composer. Pay attention to the composer API limit at GitHub though!

Leave a Reply

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