Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_replace() function

Reference for PHP array_replace() and array_replace_recursive(): replace elements by key, keep integer keys, and compare with array_merge() and the + operator.

The array_replace() function takes a base array and overwrites its elements with values from one or more replacement arrays, matching by key. Keys that do not exist in the base are added. The result is a new array.

Unlike array_merge(), it never renumbers integer keys: array_replace([0 => "a"], [0 => "b"]) replaces the element at key 0. That makes it the right tool when keys carry meaning, for example when applying overrides to a list by position.

PHP
$base = ["a", "b", "c"];
print_r(array_replace($base, [1 => "B"])); // ["a", "B", "c"]

Try it

PHP Replacing by key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP array_replace(), array_merge() and + side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_replace(array $array, array ...$replacements): array
array_replace_recursive(array $array, array ...$replacements): array
Name Description
$array The base array.
...$replacements Arrays whose elements replace or extend the base, processed left to right.

Return value: a new array. The inputs are unchanged.

Errors / Exceptions: a TypeError if an argument is not an array.

Usage notes

  • Keys are preserved, integer or string. This is the key difference from array_merge().
  • Equivalent to reversed +: array_replace($a, $b) gives the same result as $b + $a.
  • Shallow by default. A nested array in a replacement replaces the whole nested array in the base. array_replace_recursive() descends into nested arrays and replaces only the keys present.
  • In array_replace_recursive(), if the replacement value for a key is not an array, it simply replaces the base value, whatever it was.
  • Good for defaults and overrides: array_replace($defaults, $options).
  • Not the same as array_merge_recursive(), which turns clashing scalars into lists. See array_merge_recursive().