Codectionary / Developer documentation / PHP

Replace Values by Key with array_replace

Apply keyed updates while preserving numeric identifiers and understanding shallow replacement.

What it is and why to use it

An application may keep room names or settings indexed by meaningful keys. array_replace() applies later values to matching keys without renumbering integer keys. Keys that do not yet exist are added. The function returns a new array, making it useful for preparing an updated view while retaining the original data for comparison.

How it works

Each later array can overwrite entries from earlier arrays, regardless of whether a key is an integer or a string. Replacement happens at one level. When the value at a key is an array, that entire nested value is replaced; its individual children are not merged. A nested update therefore needs deliberate handling rather than an assumption that all configuration trees combine the same way.

Common mistakes and limitations

Do not confuse replacement with list appending. A value at numeric key 10 will replace key 10, not become the next list item. Do not assume that unrelated nested settings survive a shallow replacement. Inspect the resulting structure when applying configuration patches.

Run the examples locally

Save each complete example in its own example.php file and run php example.php in a terminal from that folder. Each example is independent: do not paste both into one file, especially when they declare classes with the same names. Output appears in the terminal. The examples use PHP 8.0-compatible syntax; use a currently supported PHP release for development.

The <?php opening tag starts PHP code. declare(strict_types=1) requests strict scalar argument checks for function calls made from this file; it does not validate external input for you. echo writes output, and PHP_EOL adds the platform’s line ending. Quotation marks delimit strings; they are not part of the printed text unless explicitly included in the string.

These examples use built-in PHP language features and standard extensions. They need no Composer packages, database server, browser APIs or network access. Codectionary’s PHP preview does not execute PHP; use your local interpreter to reproduce the output.

Check your interpreter, lint and run one saved example

php -v
php -l example.php
php example.php

Continue learning

Use the related guides to connect this operation to the surrounding language features. Practise by changing the example inputs and predicting the output before running it.

Syntax

$updated = array_replace($original, $changes);

Examples

Update a room name without losing its ID

Apply a correction and add a room while preserving the existing numeric keys.

<?php
declare(strict_types=1);

$rooms = [10 => 'Library', 20 => 'Lab'];
$updated = array_replace($rooms, [20 => 'Computer lab', 30 => 'Studio']);
foreach ($updated as $id => $name) {
    echo $id, ': ', $name, PHP_EOL;
}
echo $rooms[20], PHP_EOL;
  1. Key 20 matches an existing room, so its name is replaced; key 30 is new and is added.
  2. foreach prints the preserved identifiers rather than renumbered positions.
  3. The last line reads the original array, which still contains Lab. Assign the result back only when replacement of the original variable is intended.
  4. Expected output: 10: Library 20: Computer lab 30: Studio Lab

See the boundary of a shallow update

Replace one nested setting and inspect what remains.

<?php
declare(strict_types=1);

$settings = ['mail' => ['host' => 'mail.example', 'port' => 587]];
$updated = array_replace($settings, ['mail' => ['port' => 2525]]);
echo json_encode($updated, JSON_THROW_ON_ERROR), PHP_EOL;
  1. Both outer arrays contain the string key mail.
  2. The later value replaces the entire inner array, so host is absent from the result.
  3. This is a demonstration of shallow replacement, not a recommended complete mail configuration. In a real settings loader, decide which nested keys must be retained and validated.
  4. Expected output: {"mail":{"port":2525}}

Best practices

  • Use replacement when keys identify records or settings.
  • Handle nested structures explicitly and verify their resulting keys.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading