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.
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
)
)Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.