Say I have two arrays:
$arr = array('k1' => 'v1',
'k2' => 'v2');
$arr2 = array('k3' => 'v3',
'k4' => 'v4');
I want to merge $arr2 into $arr, so that I end up with:
$arr = array('k1' => 'v1',
'k2' => 'v2',
'k3' => 'v3',
'k4' => 'v4');
There is one basic requirement: the solution must change $arr itself, like functions that take a reference to the array (array_push(), array_splice()) would do.
- I don’t want to use
$arr = array_merge($arr, $arr2)because it creates a copy. -
I don’t want to iterate through $arr2 :
// this is not an option foreach ($arr2 as $k => $v) { $arr[$k] = $v; }
How can I merge two associative arrays while preserving their keys?
You can try this:
I’ve tested memory usage:
This outputs:
So while one array with 1 M elements uses about 200 MB, and the overall peak is about 400 MB, PHP apparently did not create a copy, otherwise the peak memory would be around 600 MB (
$a,$band$a + $b).