PHP array_replace()Functions
Examples
Replace the values of the first array ($a1) with the values of the second array ($a2):
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_replace($a1,$a2));
?>
Run example »
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 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 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, this element will be created in the first array array1. (See Example 2 below)
If multiple replacement arrays are passed, they will be processed in order, and the values from later arrays will overwrite the values from earlier arrays. (See Example 3 below)
Tip:Usearray_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 of valuesarray1to replace. |
| array3,... | Optional. Specifies multiple arrays of valuesarray1andarray2, ...to replace. Values from later arrays will overwrite the values 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 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.
$a1=array("a"=>"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, this element will be created in the first array array1.
$a1=array("a"=>"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):
$a1=array("red","green");
$a2=array("blue","yellow");
$a3=array("orange","burgundy");
print_r(array_replace($a1,$a2,$a3));
?>
Run example »
Example 4
Using numeric keys - If a key exists in the second array array2 but not 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));
?>
Run example »
Complete PHP Array Reference Other Extensions