Recursively replace the values of the first array ($a1) with the values of the second array ($a2):
<?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 of the first array with the values of subsequent arrays.
Tip: You can pass an array, or multiple arrays, to the function.
If a key exists in the first array array1 and also exists in the second array array2, the value in the first array array1 will be replaced by the value in the second array array2. If a key only exists in the first array array1, it will remain unchanged. If a key exists in the second array, array2, but not in the first array, array1, the element will be created in the first array, array1. If multiple replacement arrays are passed, they will be processed in order, and the values of subsequent arrays will overwrite the values of previous arrays.
Note: If you do not specify a key for each array, this function behaves identically to the array_replace() function.
array_replace_recursive( array1,array2,array3... )
parameter | describe |
---|---|
array1 | Required. Specify an array. |
array2 | Optional. Specifies an array to replace the value of array1 . |
array3,... | Optional. Specify multiple arrays to replace the values of array1 and array2, .... The values in the following array will overwrite the values in the previous array. |
Return value: | Returns the replaced array, or NULL if an error occurs. |
---|---|
PHP version: | 5.3.0+ |
Multiple arrays:
<?php$a1=array("a"=>array("red"),"b"=>array("green","blue"));$a2=array("a"=>array(" yellow"),"b"=>array("blac k"));$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);?>