Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_replace

Replaces the values of an array with values under the same keys from other arrays.

Syntax

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

Parameters

ParameterTypeDescription
$arrayarrayThe source array.
...$replacementsarrayThe arrays with the new values.

Return value

arrayA new array.

Examples

Settings on top of the defaults:

<?php
 
$defaults = ['theme' => 'light', 'size' => 14];
 
echo json_encode(array_replace($defaults, ['size' => 16]));

Output:

{"theme":"light","size":16}

The difference from array_merge() for numeric keys:

<?php
 
echo json_encode(array_replace(['a', 'b'], ['x'])), "\n";
echo json_encode(array_merge(['a', 'b'], ['x']));

Output:

["x","b"]
["a","b","x"]

Notes

array_merge() renumbers numeric keys and appends elements, while array_replace() replaces by key.

See also

In the tutorial

  • Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.

Thanks for reading!

Donate to the site — we work hard for you.