Replace the values in the first array ($a1
) with the values from the second array ($a2
).
<?php $a1=array(“red”,“green”); $a2=array(“blue”,“yellow”); print_r(array_replace($a1,$a2)); ?> |
The array_replace()
function updates the values in the first array with values from subsequent arrays.
Tip: You can pass one or more arrays to the function.
If a key from the first array exists in the second array, its value in the first array will be replaced by the value from the second array. If a key exists only in the first array, it remains unchanged (see Example 1).
If a key exists in the second array but not in the first array, it will be added to the first array (see Example 2).
When multiple arrays are provided, values from later arrays will overwrite those from earlier arrays (see Example 3).
Tip: To replace values recursively, use array_replace_recursive()
.
array_replace(array1, array2, array3, …) |
Parameter |
Description |
array1 |
Required. Specifies an array. |
array2 |
Optional. Specifies an array that will overwrite the values in the first array. |
array3,… |
Optional. Specifies additional arrays to replace the values in the previous arrays. Values from later arrays will overwrite those from earlier ones. |
Return Value: |
Returns the updated array with replaced values, or |
PHP Version: |
5.3.0+ |
If a key is present in array1 but not in array2, or if a key from array1 exists in array2:
<?php $a1=array(“a”=>“red”,“b”=>“green”); $a2=array(“a”=>“orange”,“burgundy”); print_r(array_replace($a1,$a2)); ?> |
If a key is present in array2 but not in array1:
<?php $a1=array(“a”=>“red”,“green”); $a2=array(“a”=>“orange”,“b”=>“burgundy”); print_r(array_replace($a1,$a2)); ?> |
When using three arrays, the last array ($a3
) will overwrite the values from 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)); ?> |
When using numeric keys, if a key is present in array2 but not in array1:
<?php $a1=array(“red”,“green”,“blue”,“yellow”); $a2=array(0=>“orange”,3=>“burgundy”); print_r(array_replace($a1,$a2)); ?> |