array_replace
array_replace(array $array, array ...$replacements): array
Later arrays overwrite earlier ones key by key, returning a new array: assignment-replacement, not recursive merging — nested arrays are swapped wholesale (timeout disappears), the shallow counterpart of the existing array_replace_recursive's deep merge.
C C23
#include <stdio.h>
#include <string.h>
typedef struct {
const char *key;
int val;
} Entry;
static int find(Entry *a, int n, const char *k) {
for (int i = 0; i < n; i++) {
if (strcmp(a[i].key, k) == 0) {
return i;
}
}
return -1;
}
/* array_replace = find-and-assign: patch wins key by key, no recursion */
int main(void) {
Entry base[] = {{"host", 0}, {"port", 3306}, {"conn", 4}};
Entry patch[] = {{"port", 5432}};
for (size_t i = 0; i < sizeof patch / sizeof patch[0]; i++) {
int j = find(base, 3, patch[i].key);
if (j >= 0) {
base[j].val = patch[i].val;
}
}
printf("%d\n", base[find(base, 3, "port")].val); /* 5432: replaced */
printf("%d\n", base[find(base, 3, "conn")].val); /* 4: untouched */
return 0;
}
5432 4
C++ C++26
#include <iostream>
#include <map>
#include <string>
// map::insert_or_assign IS array_replace per key: assign, never merge
int main() {
std::map<std::string, int> base{{"port", 3306}, {"conn", 4}};
std::map<std::string, int> patch{{"port", 5432}};
for (const auto &[k, v] : patch) {
base.insert_or_assign(k, v);
}
std::cout << base["port"] << " " << base["conn"] << "\n"; // 5432 4 - only "port" replaced
return 0;
}
5432 4
C# v11.0.100
using System;
using System.Collections.Generic;
// no single call: array_replace is a foreach-assign over the patch
var baseDict = new Dictionary<string, object> { ["host"] = "localhost", ["port"] = 3306 };
var patch = new Dictionary<string, object> { ["port"] = 5432 };
var merged = new Dictionary<string, object>(baseDict); // copy first: PHP never touches its inputs
foreach (var kv in patch) {
merged[kv.Key] = kv.Value; // later wins, key by key - no recursion
}
Console.WriteLine(merged["host"] + " " + merged["port"]);
Console.WriteLine(baseDict["port"]); // 3306 untouched
localhost 5432 3306
Go v1.27.4
package main
import "fmt"
// std has no one-call replace for maps: array_replace is a two-loop assign
func main() {
base := map[string]any{"host": "localhost", "port": 3306}
patch := map[string]any{"port": 5432}
merged := make(map[string]any, len(base)+len(patch))
for k, v := range base {
merged[k] = v
}
for k, v := range patch { // later wins, key by key - no recursion
merged[k] = v
}
fmt.Println(merged["host"], merged["port"])
fmt.Println(base["port"]) // 3306 untouched
}
localhost 5432 3306
Java v27.0.1
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Object> base = new LinkedHashMap<>();
base.put("host", "localhost");
base.put("port", 3306);
Map<String, Object> patch = new LinkedHashMap<>();
patch.put("port", 5432);
Map<String, Object> merged = new LinkedHashMap<>(base);
merged.putAll(patch); // putAll IS array_replace: later map wins key by key
System.out.println(merged.get("host") + " " + merged.get("port"));
System.out.println(base.get("port")); // 3306 - putAll never touches the source
}
}
localhost 5432 3306
JavaScript v26.13.1
// Object.assign / spread IS array_replace: shallow overwrite, later wins
const base = { host: "localhost", port: 3306 };
const patch = { port: 5432 };
const merged = { ...base, ...patch }; // copy first: PHP never touches its inputs
console.log(merged.host, merged.port);
console.log(base.port); // 3306 - the source object intact
// nested objects would be REPLACED wholesale (reference assignment, no merge)
localhost 5432 3306
PHP v8.6.0
// array_replace(): later arrays overwrite earlier ones key by key -
// assignment, not merge. The recursive cousin (array_replace_recursive,
// see the existing merge/replace-recursive entry) digs into sub-arrays.
$base = ["host" => "localhost", "port" => 3306, "opts" => ["ssl" => false, "timeout" => 5]];
$patch = ["port" => 5432, "opts" => ["ssl" => true]];
print_r(array_replace($base, $patch)); // "opts" REPLACED wholesale: timeout is gone
print_r(array_replace_recursive($base, $patch)); // deep variant: ssl AND timeout survive
var_dump($base["port"]); // 3306 - inputs are untouched (value semantics)
Array
(
[host] => localhost
[port] => 5432
[opts] => Array
(
[ssl] => 1
)
)
Array
(
[host] => localhost
[port] => 5432
[opts] => Array
(
[ssl] => 1
[timeout] => 5
)
)
int(3306)
Python v3.15.2
base = {"host": "localhost", "port": 3306, "opts": {"ssl": False, "timeout": 5}}
patch = {"port": 5432, "opts": {"ssl": True}}
merged = dict(base) # copy first: PHP never touches its inputs
merged.update(patch) # update IS array_replace: shallow overwrite, "opts" wholesale
print(merged["port"], merged["opts"])
print(base["port"]) # 3306 - the original dict intact
# deep merge is hand-written (loop over keys, recurse when both values are dicts)
5432 {'ssl': True}
3306
Rust v1.99.1
use std::collections::HashMap;
// extend = later keys overwrite: array_replace on maps (values move wholesale)
fn main() {
let mut base: HashMap<&str, i32> = HashMap::from([("port", 3306), ("conn", 4)]);
let patch = HashMap::from([("port", 5432)]);
base.extend(patch);
println!("{} {}", base["port"], base["conn"]); // 5432 4 - only "port" replaced
}
5432 4
TypeScript v26.13.1
// Object.assign / spread IS array_replace: shallow overwrite, later wins
const base: { host: string; port: number } = { host: "localhost", port: 3306 };
const patch: { port: number } = { port: 5432 };
const merged: { host: string; port: number } = { ...base, ...patch }; // copy first: PHP never touches its inputs
console.log(merged.host, merged.port);
console.log(base.port); // 3306 - the source object intact
// nested objects would be REPLACED wholesale (reference assignment, no merge)
localhost 5432 3306
Language differences
Shallow replace vs deep recursion: the existing array_merge_recursive_replace entry (A31) has array_replace_recursive descending into sub-arrays and merging key by key (ssl AND timeout coexist), while this entry's array_replace is assign-to-replace — the opts array is swapped wholesale and timeout is simply lost; the deterministic assertions: after merging port=5432, opts={ssl:1} (shallow, timeout dropped), the deep variant opts={ssl:1,timeout:5}, and the untouched base["port"]=3306 — fixed inputs, identical everywhere.
PHP: array_replace($a, ...$replacements) overwrites key by key left to right and returns a new array; numeric keys follow the same later-wins rule (unlike array_merge's append semantics for numeric keys); since 7.4 a spread can replace the multi-arg form.
Python: dict.update is 1:1 in semantics (shallow overwrite, returns None, mutates in place) — copy with dict(base) first, then update, to get PHP's "returns new array, inputs untouched"; deep merging has no std function (PEP 584's | merge is also shallow) and needs a handwritten recursion.
Go: maps have no single-call replace — two range-loop passes are the whole story; maps.Copy (Go 1.21+, dst must already exist) is the std-library version of the second loop.
Java: Map.putAll matches 1:1 (later map wins per key, shallow); LinkedHashMap preserves insertion order.
C#: no single call — a foreach assignment, or construct a Dictionary copy then overwrite; ImmutableDictionary.SetRange is the immutable-style variant.
JavaScript/TypeScript: the spread {...base, ...patch} and Object.assign({}, base, patch) are both shallow replacement — nested objects are swapped wholesale by reference; "returns new object, inputs untouched" naturally matches PHP's value semantics.
C: a struct array with handwritten find-and-assign — this IS the essence of array_replace (per-key lookup plus assignment); the append-when-new-key behavior is handled by the find-returns--1 branch outside the example.
C++: map::insert_or_assign (C++17) is array_replace per key; from C++26, map::insert_range pours in a whole range at once.
Rust: HashMap::extend (= per-key insert) is shallow replacement; values move in wholesale (nested structures are never merged recursively — matching PHP's shallow semantics).