Backend Development 3 min read

Using array_replace_recursive to Recursively Replace Elements in PHP Arrays

array_replace_recursive is a PHP function that recursively replaces elements of the first array with values from subsequent arrays, handling nested arrays and scalar values, and this article explains its behavior, parameters, return value, and provides a complete example with code and output.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using array_replace_recursive to Recursively Replace Elements in PHP Arrays

Explanation

The array_replace_recursive() function replaces the values of the first array with values from subsequent arrays. If a key exists in both arrays, the value from the later array overwrites the earlier one. Keys present only in later arrays are added, and keys present only in the first array remain unchanged. The operation is recursive, so nested arrays are processed in the same manner.

Parameters

array $array1 – The array whose values will be replaced.

array $array2 – The array providing replacement values.

...$arrays – Optional additional arrays to merge, processed in order.

Return value

Returns an array containing the merged values, or NULL if an error occurs.

Example

<?php
$base = array(
    'citrus' => array('orange'),
    'berries' => array('blackberry', 'raspberry')
);

$replacements = array(
    'citrus' => array('pineapple'),
    'berries' => array('blueberry')
);

$basket = array_replace_recursive($base, $replacements);
print_r($basket);
?>

Output

Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )
)
backend developmentphpphp-functionsarray_replace_recursiverecursive array merge
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.