In lots of cases I use array_merge to merge two arrays together to form a bigger array from the two, and this function works fine if you don’t need worry about the keys. However, this function will cause bugs that are hard to find if keys are important, as it will re-number all the values with the numeric keys from zero in the result array. Luckily, there is another way to add arrays and keep their keys in at the same time. It is called “+”/Union operator. It is really simple, you just need to add them together:
$resultArray = $array1 + $array2;
However, $array2 with the same keys will not overwrite the values in $array1. The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten. And remember that
$resultArray = $array1 + $array2;
$resultArray = $array2 + $array1;
will not necessarily return the same result. For more reference, please consult php documentation. Also thanks to Craig Lotter’s post on this topic.

Leave a Reply

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