array_replace
Replaces the values of an array with values under the same keys from other arrays.
Syntax
array_replace(array $array, array ...$replacements): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The source array. |
| ...$replacements | array | The 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
- array_merge — Merges one or more arrays into one.
In the tutorial
- Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.