Categories
PHP Programming

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s