PHP array_replace () function
Examples
A second array ($ a2) a first array of replacement value ($ a1) values:
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_replace($a1,$a2));
?>
Running instance »
Definition and Usage
array_replace () function uses the array later replaced with the value value of the first 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. (See example 1)
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. (See example 2)
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. (See example 3)
Tip: Use array_replace_recursive () recursively using the end of the array values with the first value of the array.
grammar
参数 | 描述 |
---|---|
array1 | 必需。指定一个数组。 |
array2 | 可选。指定一个要替换 array1 的值的数组。 |
array3,... | 可选。指定多个要替换 array1 和 array2, ... 的值的数组。后面数组的值将覆盖之前数组的值。 |
technical details
return value: | Returns array is replaced, if an error occurs it returns NULL. |
---|---|
PHP version: | 5.3.0+ |
More examples
Example 1
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.
$a1=array("a"=>"red","b"=>"green");
$a2=array("a"=>"orange","burgundy");
print_r(array_replace($a1,$a2));
?>
Running instance »
Example 2
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.
$a1=array("a"=>"red","green");
$a2=array("a"=>"orange","b"=>"burgundy");
print_r(array_replace($a1,$a2));
?>
Running instance »
Example 3
Use an array of three - the last array ($ a3) overwrites the previous array ($ a1 and $ a2):
$a1=array("red","green");
$a2=array("blue","yellow");
$a3=array("orange","burgundy");
print_r(array_replace($a1,$a2,$a3));
?>
Running instance »
Example 4
Use the numeric keys - if a key exists in the second array array2, but does not exist in the first array array1, this element will be created in the first array array1:
$a1=array("red","green","blue","yellow");
$a2=array(0=>"orange",3=>"burgundy");
print_r(array_replace($a1,$a2));
?>
Running instance »
Complete PHP Array Reference