PHP array_merge() Function Improvement

The array_merge() function in PHP is a handy way of adding one or more arrays together. Here is an example of how to use it.

$array1 = array(3, 21, 12); // set up first array
$array2 = array(63, 1, 9); // set up second array
$array3 = array_merge($array1, $array2); // merge arrays
print_r($array3); // print!

This will print the following.

Array
(
 [0] => 3
 [1] => 21
 [2] => 12
 [3] => 63
 [4] => 1
 [5] => 9
)

The only problem with this function is that it resets any numeric keys, so the following example would produce the wrong result.

$array1 = array(2 => 3, 45 => 21, 55 => 12);
$array2 = array(22 => 63, 42 => 1, 1 => 9);
$array3 = array_merge($array1, $array2);
print_r($array3);

This prints exactly the same thing as the previous example. So in order to stop resetting the keys when you merge arrays you would need to use the following function that merges arrays and keeps the keys intact.

function array_merge_keys(){
 $args = func_get_args();
 $result = array();
 foreach ($args as &$array) {
  foreach ($array as $key=>&$value) {
   $result[$key] = $value;
  }
 }
 return $result;
}

You can use this in just the same way as array_merge().

$array3 = array_merge_keys($array1, $array2);

This produces the following result.

Array
(
 [2] => 3
 [45] => 21
 [55] => 12
 [22] => 63
 [42] => 1
 [1] => 9
)

All of the array keys are intact. However, if two keys overlap then it is the last added key that takes precedence.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
4 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.