In this tutorial, you shall learn about PHP array_replace() function which can update the values in this array with values from other array based on keys, with syntax and examples.
PHP array_replace() Function
The PHP array_replace() function replaces the values of an array (array1) with the values from other array(s) based on key/index.
Please note that, if you are working with indexed arrays, then the index of items will act as key.
Syntax of array_replace()
array_replace( array1, array2, array3, ...)
where
| Parameter | Description |
|---|---|
| array1 | [mandatory] Specifies an array |
| array2 | [optional] Specifies an array which will replace the values of array1 |
| array3,… | [optional] Specifies more arrays to replace the values of array1 and array2, etc. Values from later arrays will overwrite the previous ones. |
If a key from array1 exists in array2, then value for this key in array1 will be replaced by the corresponding key’s value from array2.
If a key only exists in array1, and not in any other arrays, then its value will be left as it is.
If a key exist in array2 and not in array1, then this key-value pair will be inserted in array1.
If multiple arrays (array2, array3,…) are used, values from later arrays (say array3) will overwrite the previous ones (array2).
We will go through examples for each of these scenarios.
Function Return Value
array_replace() returns the replaced array. If any error occurs during function execution, it returns NULL.
Examples
1. Replace Values in Array – Key exists in array2
In this example, we will take an array (array1) with two key value pairs. The array2 will have a key-value pair whose key "b" exists in array1. When we replace values of array1 with that of array2 using array_replace() function, the value for key "b" should be replaced in array1 by array2.
PHP Program
<?php
$array1 = array("a"=>"apple", "b"=>"banana");
$array2 = array("b"=>"berry");
$result = array_replace($array1, $array2);
print_r($result);
?>
Output
