PHP array_replace() Function
Complete PHP Array Reference Manual
Example
Replace the values of the first array ($a1) with the values of the second array ($a2):
Run Example »
Definition and Usage
The array_replace() function replaces the values of the first array with the values of the following arrays.
**Tip:** You can pass one array, or multiple arrays, to the function.
If a key exists in the first array array1 and also in the second array array2, the value in array1 will be replaced by the value from array2. If a key exists only in array1, it will be left unchanged. (See Example 1 below)
If a key exists in the second array array2 but not in the first array array1, the element will be created in array1. (See Example 2 below)
If multiple replacement arrays are passed, they are processed in order, and values from later arrays overwrite those from earlier arrays. (See Example 3 below)
**Tip:** Please use array_replace_recursive() to recursively replace the values of the first array with the values of the following arrays.
Syntax
array_replace(
array1,array2,array3...
)
| Parameters | Description |
|---|---|
| array1 | Required. Specifies an array. |
| array2 | Optional. Specifies one array to replace array1 of the array. |
| array3,... | Optional. Specifies multiple arrays to replace array1 and array2, ... the values of. Values from later arrays overwrite those from earlier arrays. |
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 the first array array1 and also in the second array array2, the value in array1 will be replaced by the value from array2. If a key exists only in array1, it will be left unchanged.
"red","b"=>"green"); $a2=array("a"=>"orange","burgundy"); print_r(array_replace($a1,$a2)); ?>Run Example »
Example 2
If a key exists in the second array array2 but not in the first array array1, the element will be created in array1.
"red","green"); $a2=array("a"=>"orange","b"=>"burgundy"); print_r(array_replace($a1,$a2)); ?>Run Example »
Example 3
Using three arrays - the last array ($a3) will overwrite the previous arrays ($a1 and $a2):
Run Example »
Example 4
Using numeric keys - if a key exists in the second array array2 but not in the first array array1, the element will be created in array1:
"orange",3=>"burgundy"); print_r(array_replace($a1,$a2)); ?>Run Example »
Complete PHP Array Reference Manual