array_replace()

array_replace() — Replaces elements from passed arrays into the first array.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5 >= 5.3.0, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

array_replace() creates a new array and assigns items into it for each key in each of the provided arrays. If a key appears in multiple input arrays, the value from the right-most input array will be used.

Signature

array_replace(array $array, array ...$replacements): array

Parameters

ParameterTypeWhat it takes
$arrayarrayThe array in which elements are replaced.
...$replacementsarrayArrays from which elements will be extracted. Values from later arrays overwrite the previous values.

Return value

Returns an array.

Example

A runnable snippet:

$base = array("orange", "banana", "apple", "raspberry"); $replacements = array(0 => "pineapple", 4 => "cherry"); $replacements2 = array(0 => "grape"); $basket = array_replace($base, $replacements, $replacements2); var_dump($basket);

Output:

array(5) { [0]=> string(5) "grape" [1]=> string(6) "banana" [2]=> string(5) "apple" [3]=> string(9) "raspberry" [4]=> string(6) "cherry" }

See also

array_replace_recursive(), array_merge()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page array_replace() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.