PHP 8 reference · Array Functions

PHP array_replace() Function

Replace values of the first array with values that have the same keys in later arrays. Numeric keys are kept.

PHP 8 Since 5.3

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
array The input array.
replacements Arrays whose values win for the same keys.

Return value

A new array.

Examples

Replace by positionTry it yourself
<?php
print_r(array_replace(["a", "b", "c"], [1 => "B"], [3 => "d"]));

Output

Array
(
    [0] => a
    [1] => B
    [2] => c
    [3] => d
)
Compared with array_merge()Try it yourself
<?php
$defaults = [10 => "ten", 20 => "twenty"];
print_r(array_replace($defaults, [20 => "TWENTY"]));
print_r(array_merge($defaults, [20 => "TWENTY"])); // renumbers

Output

Array
(
    [10] => ten
    [20] => TWENTY
)
Array
(
    [0] => ten
    [1] => twenty
    [2] => TWENTY
)

Version history

VersionChange
PHP 5.3Added

In other languages

Was this page helpful?