array_replace in PHP

Syntax of array_replace

array array_replace(array array1, array array2[, … array arrayN])

Returns an array created by replacing values in array1 with values from the other arrays. Elements in array1 with keys matching in the replacement arrays are replaced with the values of those elements

If multiple replacement arrays are provided, they are processed in order. Any elements in array1 whose keys do not match any keys in the replacement arrays are preserved

Example of array_replace

<?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");

$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
?>
Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

Leave a Comment