PHP 8.3.21 Released!

array_merge_recursive

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

array_merge_recursiveMerge one or more arrays recursively

Description

array_merge_recursive(array ...$arrays): array

array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

Parameters

arrays

Variable list of arrays to recursively merge.

Return Values

An array of values resulted from merging the arguments together. If called without any arguments, returns an empty array.

Changelog

Version Description
7.4.0 This function can now be called without any parameter. Formerly, at least one parameter has been required.

Examples

Example #1 array_merge_recursive() example

<?php
$ar1
= array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>

The above example will output:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

See Also

add a note

User Contributed Notes 4 notes

up
175
gabriel dot sobrinho at gmail dot com
15 years ago
I refactored the Daniel's function and I got it:

<?php
/**
* array_merge_recursive does indeed merge arrays, but it converts values with duplicate
* keys to arrays rather than overwriting the value in the first array with the duplicate
* value in the second array, as array_merge does. I.e., with array_merge_recursive,
* this happens (documented behavior):
*
* array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
* => array('key' => array('org value', 'new value'));
*
* array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
* Matching keys' values in the second array overwrite those in the first array, as is the
* case with array_merge, i.e.:
*
* array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
* => array('key' => array('new value'));
*
* Parameters are passed by reference, though only for performance reasons. They're not
* altered by this function.
*
* @param array $array1
* @param array $array2
* @return array
* @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
* @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
*/
function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
$merged = $array1;

foreach (
$array2 as $key => &$value )
{
if (
is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) )
{
$merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value );
}
else
{
$merged [$key] = $value;
}
}

return
$merged;
}
?>

This fix the E_NOTICE when the the first array doesn't have the key and the second array have a value which is a array.
up
13
fantomx1 at gmail dot com
9 years ago
I little bit improved daniel's and gabriel's contribution to behave more like original array_merge function to append numeric keys instead of overwriting them and added usefull option of specifying which elements to merge as you more often than not need to merge only specific part of array tree, and some parts of array just need to let overwrite previous. By specifying helper element mergeWithParent=true, that section of array will be merged, otherwise latter array part will override former. First level of array behave as classic array_merge.

function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
static $level=0;
$merged = [];
if (!empty($array2["mergeWithParent"]) || $level == 0) {
$merged = $array1;
}

foreach ( $array2 as $key => &$value )
{
if (is_numeric($key)) {
$merged [] = $value;
} else {
$merged[$key] = $value;
}

if ( is_array ( $value ) && isset ( $array1 [$key] ) && is_array ( $array1 [$key] )
) {
$level++;
$merged [$key] = array_merge_recursive_distinct($array1 [$key], $value);
$level--;
}
}
unset($merged["mergeWithParent"]);
return $merged;
}
up
2
andrew at indigo - sphere dot co dot uk
4 years ago
An alternative solution where this function does not produce the desired output: Pass a custom recursive function to array_reduce():

For example (Using PHP 7 capabilities to create recursive anonymous function):

<?php
function array_merge_recursive(...$arrays): ?array {
return
array_reduce($arrays, new class {
public function
__invoke($carry, $item) {
if (
is_array($carry) && is_array($item) {
return
$this($carry, $item);
}
return
$item ?: $carry;
}
}
}
?>
In this case truthy values will overwrite the value in the previous array.
Of course this is presented as a simple example only, and is not a general solution.
up
0
lsiq at papotam com
14 years ago
<?php

// this function merges an array with the $_SESSION
// if you omit second parameter it merges to the root
// if you give one 'path' array it is merged deeply

function arr2sess($arr, $path=array()){
if (!
is_array($arr)) return false;
foreach(
$arr as $k => $v){
if(
is_array($arr[$k])) {
$path[] = $k;
arr2sess($arr[$k], $path);
}else{
$ref = &$_SESSION;
if(
$path){
foreach(
$path as $val){
if(!
$ref[$val]) $ref[$val] = array();
$ref = &$ref[$val];
}
}
$ref[$k] = $v;
}
}
}

session_start();
$x = array(k1=>12, k2=>array(kxx=>'forget me', kyy=>'I was allways here')); // do you have any of this on $_SESSION
$rpl = array(k2=>array(kxx=>'I am a replaced value',kzz=>'I am a new value'));
arr2sess($x, array('deep','deep','in_session')); // you can use this way
arr2sess($x); // or this
arr2sess($rpl); // to merge parts with the $_SESSION

$w = array(120, q=>array(199,100)); // works the same way on numeric keys
arr2sess($w, array('one','two'));
arr2sess($w);

echo
'<pre>';
print_r($_SESSION);

?>
To Top