PHP array_replace() Function
The PHP array_replace() function replaces the values of first array with values having the same keys in each of the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If a key only exists in the second array, it will be created in the first array. If a key only exists in the first array, it will be left as it is. If multiple arrays are used, values from later arrays will overwrite the previous ones.
Syntax
array_replace(array, replacements)
Parameters
array |
Required. Specify the array in which elements are replaced. |
replacements |
Required. Specify arrays from which elements will be extracted. Values from later arrays overwrite the previous values. |
Return Value
Returns an array, or null if an error occurs.
Exceptions
NA.
Example:
The example below shows the usage of array_replace() function.
<?php $Arr1 = array("a"=>"Red", "b"=>"Green", "c"=>"Blue"); $Arr2 = array("a"=>"Black", "b"=>"White"); $result = array_replace($Arr1, $Arr2); print_r($result); ?>
The output of the above code will be:
Array ( [a] => Black [b] => White [c] => Blue )
Example:
The example below shows the result when keys only exists in either of arrays but not in both (keys - "a", "b" and "d").
<?php $Arr1 = array("a"=>"Red", "b"=>"Green", "c"=>"Blue"); $Arr2 = array("c"=>"Black", "d"=>"White"); $result = array_replace($Arr1, $Arr2); print_r($result); ?>
The output of the above code will be:
Array ( [a] => Red [b] => Green [c] => Black [d] => White )
Example:
Consider the example below where multiple arrays are used for replacement and values from later arrays will overwrite the previous ones.
<?php $Arr1 = array("a"=>"Red", "b"=>"Red", "c"=>"Blue"); $Arr2 = array("c"=>"Black", "d"=>"Orange"); $Arr3 = array("c"=>"White"); $result = array_replace($Arr1, $Arr2, $Arr3); print_r($result); ?>
The output of the above code will be:
Array ( [a] => Red [b] => Red [c] => White [d] => Orange )
Example:
Consider one more example where indexed array is used as first array.
<?php $Arr1 = array("Red", "Blue", "Green", "Black"); $Arr2 = array("0"=>"White", "2"=>"Orange"); $Arr3 = array("0"=>"Pink"); $result = array_replace($Arr1, $Arr2, $Arr3); print_r($result); ?>
The output of the above code will be:
Array ( [0] => Pink [1] => Blue [2] => Orange [3] => Black )
❮ PHP Array Reference