PHP array_merge() Function Improvement

31st March 2008

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.

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

This will print the following.

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

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

  1. $array1 = array(2 => 3, 45 => 21, 55 => 12);
  2. $array2 = array(22 => 63, 42 => 1, 1 => 9);
  3. $array3 = array_merge($array1, $array2);
  4. 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.

  1. function array_merge_keys(){
  2. $args = func_get_args();
  3. $result = array();
  4. foreach ($args as &$array) {
  5. foreach ($array as $key=>&$value) {
  6. $result[$key] = $value;
  7. }
  8. }
  9. return $result;
  10. }

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

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

This produces the following result.

  1. Array
  2. (
  3. [2] => 3
  4. [45] => 21
  5. [55] => 12
  6. [22] => 63
  7. [42] => 1
  8. [1] => 9
  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.