PHP array_replace() function
Example
Use the values of the second array ($a2) to replace the values of the first array ($a1):
<?php $a1=array("red","green"); $a2=array("blue","yellow"); print_r(array_replace($a1,$a2)); ?>
Definition and usage
The array_replace() function uses the values of the subsequent array to replace the values of the first array.
Tip:You can pass an array, or multiple arrays, to the function.
If a key exists in the first array array1 also exists in the second array array2The first array array1 will be overwritten by the second array array2 to replace the value. If a key only exists in the first array array1it will remain unchanged. (See the example below 1)
If a key exists in the second array array2exists, but does not exist in the first array array1If it exists in the first array array1 to create this element. (See the example below 2)
If multiple replacement arrays are passed, they will be processed in order, and the values of the subsequent array will overwrite the values of the previous array. (See the example below 3)
Tip:Please use array_replace_recursive() to recursively use the values of the subsequent array to replace the values of the first array.
Syntax
array_replace(array1,array2,array3...)
Parameter | Description |
---|---|
array1 | Required. Defines an array. |
array2 | Optional. Specify the replacement array1 The array of values. |
array3,... | Optional. Specify multiple replacements array1 and array2The array of values of ... . The values of the subsequent array will overwrite the values of the previous array. |
Technical details
Return value: | Returns the replaced array, or NULL if an error occurs. |
PHP Version: | 5.3.0+ |
More Examples
Example 1
If a key exists in array1 Also exists in array2 In, the value of the first array will be replaced by the value in the second array:
<?php $a1=array("a"=>"red","b"=>"green"); $a2=array("a"=>"orange","burgundy"); print_r(array_replace($a1,$a2)); ?>
Example 2
If a key exists only in the second array:
<?php $a1=array("a"=>"red","green"); $a2=array("a"=>"orange","b"=>"burgundy"); print_r(array_replace($a1,$a2)); ?>
Example 3
Use Three Arrays - The last array ($a3) will override the previous arrays ($a1 and $a2):
<?php $a1=array("red","green"); $a2=array("blue","yellow"); $a3=array("orange","burgundy"); print_r(array_replace($a1,$a2,$a3)); ?>
Example 4
Use Numeric Keys - If a key exists in the second array but not in the first array:
<?php $a1=array("red","green","blue","yellow"); $a2=array(0=>"orange",3=>"burgundy"); print_r(array_replace($a1,$a2)); ?>