Latest web development tutorials

PHP array_replace_recursive () function

PHP Array Reference Complete PHP Array Reference

Examples

Recursively using a second array ($ a2) is replaced by the value of the first array ($ a1) values:

<?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));
?>

Running instance »

Definition and Usage

array_replace_recursive () function recursively using the end of the array values ​​with the first value of the array.

Tip: You can pass an array to a function, or multiple arrays.

If a key is present in the first array is also present in the second array1 array array2, array1 The first array value will be replaced in the second array array2 value. If a key exists only in the first array array1, it will remain unchanged. If a key is present in the second array array2, but does not exist in the first array array1, this element will be created in the first array of array1. If you pass an array of a plurality of replacement, they will be processed sequentially in the order, behind the value of the array will overwrite the previous value of the array.

NOTE: If you do not specify a key for each array, the behavior of the function will be equivalent to array_replace () function.


grammar

array_replace_recursive( array1,array2,array3... )

参数 描述
array1 必需。指定一个数组。
array2 可选。指定一个要替换 array1 的值的数组。
array3,... 可选。指定多个要替换 array1array2, ... 的值的数组。后面数组的值将覆盖之前数组的值。

technical details

return value: Returns array is replaced, if an error occurs it returns NULL.
PHP version: 5.3.0+


More examples

Example 1

A plurality of 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));
?>

Running instance »

Example 2

Different array_replace () and array_replace_recursive () between:

<?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);
?>

Running instance »

PHP Array Reference Complete PHP Array Reference