PHP Tutorial - PHP array_replace_recursive() Function






Definition

The array_replace_recursive() function replaces the values of the first array with the values from following arrays recursively.

Syntax

PHP array_replace_recursive() Function has the following syntax.

array_replace_recursive(array1,array2,array3...)

Parameter

ParameterIs RequiredDescription
array1Required.Array to be replaced
array2Optional.Array to replace array1
array3,...Optional.Array to replace array before array3(array1,array2)

Example 1

Replaces the values of the first array with the values from following arrays recursively


<?php
    $a1=array("a"=>array("A"),"b"=>array("Java","PHP"),);
    $a2=array("a"=>array("B"),"b"=>array("HTML"));
    print_r(array_replace_recursive($a1,$a2));
?>

The code above generates the following result.





Example 2

Multiple arrays:


<?php
    $a1=array("a"=>array("A"),"b"=>array("Java","PHP"),);
    $a2=array("a"=>array("B"),"b"=>array("HTML"));
    $a3=array("a"=>array("C"),"b"=>array("CSS"));
    print_r(array_replace_recursive($a1,$a2,$a3));
?>

The code above generates the following result.

Example 3

Differences between array_replace() and array_replace_recursive():


<?php// ww w.jav a  2  s.  c  om
    $a1=array("a"=>array("A"),"b"=>array("Java","PHP"),);
    $a2=array("a"=>array("B"),"b"=>array("HTML"));
    
    $result=array_replace_recursive($a1,$a2);
    print_r($result);
    
    $result=array_replace($a1,$a2);
    print_r($result);
?>

The code above generates the following result.