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.

 "hi");
$array2 = array(3 => "data");
$result = array_merge($array1, $array2);
?>

Result:
Array
(
    [0] => hi
    [1] => data
)

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:

 

 "hi");
$array2 = array(3 => "data");
$result = $array1 + $array2;
?>

Result:
Array
(
    [2] => hi
    [3] => data
)

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

Comments

One response to “PHP: How to array_merge Without Losing Numeric Keys”

  1. Alejandro Avatar

    Thanks for this post John. Although the solution has been simple, you have solved a problem that was bothering me. Thanks again.

    Like

Leave a reply to Alejandro Cancel reply