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
Syntax
array_replace(array $array, array ...$replacements): array
Parameters
| Parameter | Description |
|---|---|
array |
The input array. |
replacements |
Arrays whose values win for the same keys. |
Return value
A new array.
Examples
<?php
print_r(array_replace(["a", "b", "c"], [1 => "B"], [3 => "d"]));
Output
Array
(
[0] => a
[1] => B
[2] => c
[3] => d
)<?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
| Version | Change |
|---|---|
| PHP 5.3 | Added |
In other languages
dict.update()· PythonObject.assign()· JavaScript
Related
array_merge()· Merge one or more arrays into a new array. Numeric keys are renumbered; for string keys the later value wins.array_merge_recursive()· Merge arrays and, when string keys clash, combine their values into arrays instead of overwriting.- PHP Arrays · tutorial
- PHP Array Functions · tutorial