PHP array_replace_recursive()Functions
Examples
Recursively use the values of the second array ($a2) to replace the values of the first array ($a1):
$a1=array("a"=>array("red"),"b"=>array("green","blue"),);
$a2=array("a"=>array("yellow"),"b"=>array("black"));
print_r(array_replace_recursive($a1,$a2));
?>
Run Example »
Definition and Usage
The array_replace_recursive() function recursively replaces the values of the first array with the values of the later arrays.
Tip:You can pass one array, or multiple arrays, to the function.
If a key exists in both the first array array1 and 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 exists only 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, this element will be created in the first array array1. If multiple replacement arrays are passed, they will be processed sequentially, and the values of later arrays will overwrite the values of previous arrays.
Note:If no key is specified for each array, the behavior of this function will be the same as array_replace()function.
Syntax
| Parameter | Description |
|---|---|
| array1 | Required. Specifies an array. |
| array2 | Optional. Specifies an array to replacearray1the array of values. |
| array3,... | Optional. Specifies multiple arrays to replacearray1andarray2, ...the array of values. The values of later arrays will overwrite the values of 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:
$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));
?>
Run Example »
Example 2
The difference between array_replace() and array_replace_recursive():
$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);
?>
Run Example »
Complete PHP Array Reference Other Extensions