The array_replace() function replaces the values of the first array with the values from following arrays.
PHP array_replace() Function has the following syntax.
array_replace(array1,array2,array3...)
Parameter | Is Required | Description |
---|---|---|
array1 | Required. | Array to replace |
array2 | Optional. | Array to replace array1 |
array3,... | Optional. | Array to replace array1 and array2, etc. |
Replaces the values of the first array with the values from following arrays
<?php
$a1=array("A","C");
$a2=array("B","D");
print_r(array_replace($a1,$a2));
?>
The code above generates the following result.
If a key from array1 exists in array2, and if the key only exists in array1:
<?php
$a1=array("p"=>"PHP","j"=>"Java");
$a2=array("p"=>"Python");
print_r(array_replace($a1,$a2));
?>
The code above generates the following result.
If a key exists in array2 and not in array1:
<?php
$a1=array("a"=>"red","java2s.com");
$a2=array("c"=>"orange","d"=>"burgundy");
print_r(array_replace($a1,$a2));
?>
The code above generates the following result.
Using three arrays - the last array ($a3) will overwrite the previous ones ($a1 and $a2):
<?php
$a1=array("A","B");
$a2=array("A","java2s.com");
$a3=array("B","F");
print_r(array_replace($a1,$a2,$a3));
?>
The code above generates the following result.
Using numeric keys - If a key exists in array2 and not in array1:
<?php
$a1=array("A","B","C","D");
$a2=array(0=>"java2s.com",30=>"PHP");
print_r(array_replace($a1,$a2));
?>
The code above generates the following result.