Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge array and preserve keys?

Tags:

arrays

php

I have two arrays:

$array1 = array('a' => 1, 'b' => 2, 'c' => 3); $array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456); 

I want to merge them and keep the keys and the order and not re-index!!

How to get like this?

Array (     [a] => new value     [b] => 2     [c] => 3     [d] => 4     [e] => 5     [f] => 6     [123] => 456 ) 

I try to array_merge() but it will not be preserved the keys:

print_r(array_merge($array1, $array2));  Array (     [a] => 'new value'     [b] => 2     [c] => 3     [d] => 4     [e] => 5     [f] => 6     [0] => 456 ) 

I try to the union operator but it will not overwriting that element:

print_r($array1 + $array2);  Array (     [a] => 1   <-- not overwriting     [b] => 2     [c] => 3     [d] => 4     [e] => 5     [f] => 6     [123] => 456 ) 

I try to swapped place but the order is wrong, not my need:

print_r($array2 + $array1);  Array (     [d] => 4     [e] => 5     [f] => 6     [a] => new value      [123] => 456     [b] => 2     [c] => 3 ) 

I dont want to use a loop, is there a way for high performance?

like image 722
Jasper Avatar asked Jul 04 '13 05:07

Jasper


People also ask

Can arrays be merged?

concat(array1, array2) to merge 2 or more arrays. These approaches are immutable because the merge result is stored in a new array. If you'd like to perform a mutable merge, i.e. merge into an array without creating a new one, then you can use array1.

What is the difference between Array_merge () and Array_merge_recursive () in PHP?

The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.


2 Answers

You're looking for array_replace():

$array1 = array('a' => 1, 'b' => 2, 'c' => 3); $array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456); print_r(array_replace($array1, $array2)); 

Available since PHP 5.3.

Update

You can also use the union array operator; it works for older versions and might actually be faster too:

print_r($array2 + $array1); 
like image 141
Ja͢ck Avatar answered Sep 27 '22 21:09

Ja͢ck


@Jack uncovered the native function that would do this but since it is only available in php 5.3 and above this should work to emulate this functionality on pre 5.3 installs

  if(!function_exists("array_replace")){       function array_replace(){          $args = func_get_args();          $ret = array_shift($args);          foreach($args as $arg){              foreach($arg as $k=>$v){                 $ret[(string)$k] = $v;              }          }          return $ret;      }  } 
like image 45
Orangepill Avatar answered Sep 27 '22 21:09

Orangepill