PHP Deep Extend Array

Sabrina Leggett picture Sabrina Leggett · Oct 4, 2012 · Viewed 7k times · Source

How can I do a deep extension of a multi dimensional associative array (for use with decoded JSON objects). I need the php equivalent of jQuery's $.extend(true, array1, array2) with arrays instead of JSON and in PHP.

Here's an example of what I need (array_merge_recursive didn't seem to do the same thing)

$array1 = ('1'=> ('a'=>'array1a', 'b'=>'array1b'));
$array2 = ('1'=> ('a'=>'array2a', 'c'=>'array2b'));

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

//$array3 = ('1'=> ('a'=>'array2a', 'b'=>'array1b', 'c'=>'array2b'))

Notice how array2 overrides array1 if it has same value (like how extension of classes works)

Answer

S P picture S P · Oct 24, 2013

If you have PHP 5.3.0+, you can use array_replace_recursive which does exactly what you need:

array_replace_recursive() replaces the values of array1 with the same values from all the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later array overwriting the previous values.