Recursively replace the values in the first array with the values from the second array.
<?php $a1=array(“a”=>array(“red”),“b”=>array(“green”,“blue”),); $a2=array(“a”=>array(“yellow”),“b”=>array(“black”)); print_r(array_replace_recursive($a1,$a2)); ?> |
The array_replace_recursive() function recursively replaces the values in the first array with values from subsequent arrays.
Tip: You can pass one or more arrays to the function.
If a key from the first array exists in the second array, its value in the first array will be replaced by the value from the second array. If a key exists only in the first array, it remains unchanged. If a key exists in the second array but not in the first array, it will be added to the first array. When multiple arrays are provided, values from later arrays will overwrite those from earlier arrays.
Note: If you do not specify keys for the arrays, this function will behave the same as array_replace().
array_replace_recursive(array1, array2, array3, …) |
Parameter |
Description |
array1 |
Required. Defines an array. |
array2 |
Optional. Specifies an array that will replace the values in the first array. |
array3,… |
Optional. Specifies additional arrays to replace the values in array1 and array2, etc. Values from later arrays will overwrite those from earlier ones. |
Return Value: |
Returns the updated array with replaced values, or |
PHP Version: |
5.3.0+ |
Multiple arrays:
<?php $a1=array(“a”=>array(“red”),“b”=>array(“green”,“blue”)); $a2=array(“a”=>array(“yellow”),“b”=>array(“black”)); $a3=array(“a”=>array(“orange”),“b”=>array(“burgundy”)); print_r(array_replace_recursive($a1,$a2,$a3)); ?> |
Differences between array_replace() and array_replace_recursive():
<?php $a1=array(“a”=>array(“red”),“b”=>array(“green”,“blue”),); $a2=array(“a”=>array(“yellow”),“b”=>array(“black”)); $result=array_replace_recursive($a1,$a2); print_r($result); $result=array_replace($a1,$a2); print_r($result); ?> |