PHP array_replace_recursive() Function

PHP array_replace_recursive Function


The array_replace_recursive() function replaces the values in an array with the values from other arrays recursively. This function is mainly used with deeper arrays (an array inside an array).


Syntax

The basic syntax of the array_replace_recursive() function is given with:

      array_replace_recursive(array1array2, ...)

Parameters

The array_replace_recursive() function accepts the following parameters.

Parameter Description
array1 Required. Specifies the array in which elements are replaced.
array2 Optional. Specifies the array from which elements will be extracted.
... Optional. Specifies more array from which elements will be extracted. Values from later arrays overwrite the previous values.

Example1 :

 

Output :

Array
(
    [Website] => Array
        (
            [0] => web
            [1] => Designing
        )

    [wilds] => Array
        (
            [0] => online
            [1] => promotiom
        )

)

The array_replace_recursive() function replaces the values of the first array with the values from the following arrays in such a way that, 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 in 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 multiple arrays are passed for the replacement, they will be processed in order, the later arrays overwriting the previous values. And, since this function is recursive, it will recurse into arrays and apply the same process to the inner values.

Example2: The following example shows what happens if several arrays are passed for replacement.

Output : 

Array
(
   [pets] => Array
        (
           [0] => rabbit
           [1] => horse
        )
    [wilds] => Array
        (
            [0] => lion
            [1] => fox
        )
)