quantumSoup
quantumSoup

Reputation: 28132

How can I merge two associative arrays while preserving their keys?

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.

How can I merge two associative arrays while preserving their keys?

Upvotes: 2

Views: 958

Answers (1)

Wolfgang Stengel
Wolfgang Stengel

Reputation: 2856

You can try this:

$arr += $arr2;

I've tested memory usage:

for ($i=0; $i<1000000; $i++) $a[]=1;
echo memory_get_peak_usage(), "\n";
for ($i=0; $i<1000000; $i++) $b[]=1;
echo memory_get_peak_usage(), "\n";
$a += $b;
echo memory_get_peak_usage(), "\n";

This outputs:

209135144
417540744
417540872

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, $b and $a + $b).

Upvotes: 3

Related Questions