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 preserve keys and order instead of re-indexing! !
How did it become like this?
Array ( [a] => new value [b] => 2 [c] => 3 [d] => 4 [e] => 5 [f] => 6 [123] => 456 )
I tried array_merge() but it doesn't preserve 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 tried using the union operator but it doesn't overwrite the element:
print_r($array1 + $array2); Array ( [a] => 1 <-- not overwriting [b] => 2 [c] => 3 [d] => 4 [e] => 5 [f] => 6 [123] => 456 )
I tried swapping places, but it was in the wrong order, not what I needed:
print_r($array2 + $array1); Array ( [d] => 4 [e] => 5 [f] => 6 [a] => new value [123] => 456 [b] => 2 [c] => 3 )
I don't want to use loops, is there a way to get high performance?
Suppose we have 3 arrays as shown below.
Now if you want to merge all these arrays and want the final array to contain all the array data under keys 0 in 0 and 1 in 1 and so on.
Then you need to use the array_replace_recursive PHP function as follows.
The results are as follows.
Hope the above solution can best suit your requirements! !
You are looking for
array_replace()
:Available since PHP 5.3.
renew
You can also use the union array operator ; it works on older versions and may actually be faster too: