array_replace_recursive in PHP

Syntax of array_replace_recursive

array array_replace_recursive(array array1, array array2[, … array arrayN])

Returns an array created by replacing values in array1 with values from the other arrays. Elements in array1 with keys matching in the replacement arrays are replaced with the values of those elements. If the value in both array1 and a replacement array for a particular key are arrays, those values in those arrays are recursively merged using the same process

If multiple replacement arrays are provided, they are processed in order. Any elements in array1 whose keys do not match any keys in the replacement arrays are preserved.

Example of array_replace_recursive

<?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);

$basket = array_replace($base, $replacements);
print_r($basket);
?>
Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

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

    [berries] => Array
        (
            [0] => blueberry
        )

)

Leave a Comment