Elective Courses
Course Recommendation:
PHP array_replace_recursive() function
<?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)); ?>
Example
Recursively use the values of the second array ($a2) to replace the values of the first array ($a1):
Definition and UsageThe array_replace_recursive() function recursively uses the values of the later array to replace the values of the first array.
Tip: array1 You can pass an array or multiple arrays to the function. array2If a key exists in the first array array1 Also exists in the second array array2 The value in the second array array1in the value of the first array array2, it will remain unchanged. If a key exists in the second array array1, but does not exist in the first array array1 Create this element in the middle. If multiple replacement arrays are passed, they will be processed in order, and the values of the later arrays will overwrite the values of the earlier arrays.
Note:If no key is specified for each array, the behavior of the function will be equivalent to array_replace() function.
Syntax
array_replace_recursive(array1,array2,array3...)
Parameters | Description |
---|---|
array1 | Required. Defines the array. |
array2 | Optional. Specify the array to replace array1 with the values of the arrays. |
array3,... | Optional. Specify multiple arrays to replace array1 and array2An array of values of ..., where the values of the subsequent arrays will overwrite the values of the previous arrays. |
Technical Details
Return Value: | Returns the replaced array, or NULL if an error occurs. |
PHP Version: | 5.3.0+ |
More Examples
Example 1
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)); ?>
Example 2
The Difference 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); ?>