PHP array_replace()
Function
Complete PHP Array Reference Manual
Example
Replace the values of the first array ($a1) with the values from the second array ($a2):
Definition and Usage
The array_replace()
function replaces the values of the first array with the values from subsequent arrays.
Tip: You can pass one or multiple arrays to the function.
If a key exists in the first array array1 and also exists in 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. (See Example 1 below)
If a key exists in the second array array2 but not in the first array array1, it will be created in the first array array1. (See Example 2 below)
If multiple replacement arrays are passed, they will be processed in sequence, with the values from later arrays overriding those from earlier arrays. (See Example 3 below)
Tip: Use array_replace_recursive() to recursively replace the values of the first array with the values from subsequent arrays.
Syntax
Parameter | Description |
---|---|
array1 | Required. Specifies an array. |
array2 | Optional. Specifies an array to replace the values of array1. |
array3,... | Optional. Specifies multiple arrays to replace the values of array1 and array2, etc. Values from later arrays will override 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 exists in 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.
Example 2
If a key exists in the second array array2 but not in the first array array1, it will be created in the first array array1.
Example 3
Using three arrays - the last array ($a3) will override the previous arrays ($a1 and $a2):
Example 4
Using numeric keys - if a key exists in the second array array2 but not in the first array array1, it will be created in the first array array1: