array_merge_recursive / array_replace_recursive

array_merge_recursive(array ...$arrays): array — array_replace_recursive(array ...$arrays): array

Recursive merging and replacing of nested arrays: merge_recursive aggregates colliding scalar values into an array (port becomes [3306,5432]), while replace_recursive lets the later array overwrite deep down. Neither mutates the originals — the behavioral contrast is the key point when merging configs.

C C23

C23
#include <stdio.h>
#include <string.h>
#include "cJSON.h"

// merge_recursive analogue: same key with scalar values becomes an array of both, a first
static cJSON *merge_recursive(const cJSON *a, const cJSON *b) {
    if (cJSON_IsObject(a) && cJSON_IsObject(b)) {
        cJSON *out = cJSON_Duplicate(a, 1);
        const cJSON *bv = NULL;
        cJSON_ArrayForEach(bv, b) {
            const cJSON *av = cJSON_GetObjectItemCaseSensitive(a, bv->string);
            if (av) {
                cJSON_ReplaceItemInObject(out, bv->string, merge_recursive(av, bv));
            } else {
                cJSON_AddItemToObject(out, bv->string, cJSON_Duplicate(bv, 1));
            }
        }
        return out;
    }
    if (a && b) { // both scalars: wrap into a two-element array
        cJSON *arr = cJSON_CreateArray();
        cJSON_AddItemToArray(arr, cJSON_Duplicate(a, 1));
        cJSON_AddItemToArray(arr, cJSON_Duplicate(b, 1));
        return arr;
    }
    return cJSON_Duplicate(a ? a : b, 1);
}

// replace_recursive analogue: b wins key by key, recursing into nested objects
static cJSON *replace_recursive(const cJSON *a, const cJSON *b) {
    if (cJSON_IsObject(a) && cJSON_IsObject(b)) {
        cJSON *out = cJSON_Duplicate(a, 1);
        const cJSON *bv = NULL;
        cJSON_ArrayForEach(bv, b) {
            const cJSON *av = cJSON_GetObjectItemCaseSensitive(a, bv->string);
            if (av) {
                cJSON_ReplaceItemInObject(out, bv->string, replace_recursive(av, bv));
            } else {
                cJSON_AddItemToObject(out, bv->string, cJSON_Duplicate(bv, 1));
            }
        }
        return out;
    }
    return cJSON_Duplicate(b ? b : a, 1);
}

int main(void) {
    cJSON *a = cJSON_Parse("{\"db\":{\"host\":\"localhost\",\"port\":3306},\"debug\":true}");
    cJSON *b = cJSON_Parse("{\"db\":{\"port\":5432,\"ssl\":\"on\"}}");
    char *m = cJSON_PrintUnformatted(merge_recursive(a, b));
    char *r = cJSON_PrintUnformatted(replace_recursive(a, b));
    printf("%s\n%s\n", m, r);
    cJSON_free(m); cJSON_free(r);
    cJSON_Delete(a); cJSON_Delete(b);
    return 0;
}
Output
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

C++ C++26

C++26
#include <iostream>
#include "nlohmann/json.hpp"
using nlohmann::json;

// merge_recursive analogue: same key with scalar values becomes an array of both, a first
json merge_recursive(const json &a, const json &b) {
    if (a.is_object() && b.is_object()) {
        json out = a;
        for (auto &[k, v] : b.items()) {
            if (out.contains(k) && out[k].is_object() && v.is_object())
                out[k] = merge_recursive(out[k], v);
            else if (out.contains(k) && !v.is_object())
                out[k] = json::array({out[k], v});
            else
                out[k] = v;
        }
        return out;
    }
    return b;
}

// replace_recursive analogue: b wins key by key, recursing into nested objects
json replace_recursive(const json &a, const json &b) {
    if (a.is_object() && b.is_object()) {
        json out = a;
        for (auto &[k, v] : b.items()) {
            out[k] = (out.contains(k) && out[k].is_object() && v.is_object())
                         ? replace_recursive(out[k], v)
                         : v;
        }
        return out;
    }
    return b;
}

int main() {
    json a = {{"db", {{"host", "localhost"}, {"port", 3306}}}, {"debug", true}};
    json b = {{"db", {{"port", 5432}, {"ssl", "on"}}}};
    std::cout << merge_recursive(a, b).dump() << "\n";
    std::cout << replace_recursive(a, b).dump() << "\n";
    return 0;
}
Output
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

C# v11.0.100

v11.0.100
using System.Text.Json;

var a = new SortedDictionary<string, object> {
    ["db"] = new SortedDictionary<string, object> { ["host"] = "localhost", ["port"] = 3306 },
    ["debug"] = true,
};
var b = new SortedDictionary<string, object> {
    ["db"] = new SortedDictionary<string, object> { ["port"] = 5432, ["ssl"] = "on" },
};

// no builtin deep merge in the standard library: hand-written recursion
SortedDictionary<string, object> Merge(SortedDictionary<string, object> x, SortedDictionary<string, object> y) {
    var out_ = new SortedDictionary<string, object>(x);
    foreach (var (k, v) in y) {
        if (out_.TryGetValue(k, out var old) && old is SortedDictionary<string, object> od && v is SortedDictionary<string, object> vd)
            out_[k] = Merge(od, vd);
        else if (out_.ContainsKey(k) && v is not SortedDictionary<string, object>)
            out_[k] = new List<object> { old!, v }; // scalar collision becomes an array of both
        else
            out_[k] = v;
    }
    return out_;
}

SortedDictionary<string, object> Replace(SortedDictionary<string, object> x, SortedDictionary<string, object> y) {
    var out_ = new SortedDictionary<string, object>(x);
    foreach (var (k, v) in y)
        out_[k] = out_.TryGetValue(k, out var old) && old is SortedDictionary<string, object> od && v is SortedDictionary<string, object> vd
            ? Replace(od, vd)
            : v; // b wins deep down
    return out_;
}

Console.WriteLine(JsonSerializer.Serialize(Merge(a, b)));
Console.WriteLine(JsonSerializer.Serialize(Replace(a, b)));
Output
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

Go v1.27.4

v1.27.4
package main

import (
	"encoding/json"
	"fmt"
)

func merge(a, b map[string]any) map[string]any {
	out := map[string]any{}
	for k, v := range a {
		out[k] = v
	}
	for k, v := range b {
		old, exists := out[k]
		ao, aok := old.(map[string]any)
		bo, bok := v.(map[string]any)
		switch {
		case !exists:
			out[k] = v
		case aok && bok: // both nested maps: recurse
			out[k] = merge(ao, bo)
		default: // any other collision: an array of both, a first
			out[k] = []any{old, v}
		}
	}
	return out
}

func replace(a, b map[string]any) map[string]any {
	out := map[string]any{}
	for k, v := range a {
		out[k] = v
	}
	for k, v := range b {
		if ao, aok := out[k].(map[string]any); aok {
			if bo, bok := v.(map[string]any); bok {
				out[k] = replace(ao, bo)
				continue
			}
		}
		out[k] = v // b wins
	}
	return out
}

func main() {
	a := map[string]any{"db": map[string]any{"host": "localhost", "port": 3306}, "debug": true}
	b := map[string]any{"db": map[string]any{"port": 5432, "ssl": "on"}}
	ma, _ := json.Marshal(merge(a, b))
	ra, _ := json.Marshal(replace(a, b))
	fmt.Println(string(ma))
	fmt.Println(string(ra))
}
Output
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

Java v27.0.1

v27.0.1
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    @SuppressWarnings("unchecked")
    static Map<String, Object> merge(Map<String, Object> a, Map<String, Object> b) {
        Map<String, Object> out = new LinkedHashMap<>(a);
        for (var e : b.entrySet()) {
            Object old = out.get(e.getKey());
            boolean bothMaps = old instanceof Map && e.getValue() instanceof Map;
            if (bothMaps)
                out.put(e.getKey(), merge((Map<String, Object>) old, (Map<String, Object>) e.getValue()));
            else if (out.containsKey(e.getKey()))
                out.put(e.getKey(), List.of(old, e.getValue())); // scalar collision -> array of both, a first
            else
                out.put(e.getKey(), e.getValue());
        }
        return out;
    }

    @SuppressWarnings("unchecked")
    static Map<String, Object> replace(Map<String, Object> a, Map<String, Object> b) {
        Map<String, Object> out = new LinkedHashMap<>(a);
        for (var e : b.entrySet()) {
            Object old = out.get(e.getKey());
            out.put(e.getKey(), old instanceof Map && e.getValue() instanceof Map
                    ? replace((Map<String, Object>) old, (Map<String, Object>) e.getValue())
                    : e.getValue()); // b wins deep down
        }
        return out;
    }

    // minimal compact-JSON serializer: LinkedHashMap order is preserved
    static String json(Object v) {
        if (v instanceof Map<?, ?> m) {
            StringBuilder sb = new StringBuilder("{");
            int i = 0;
            for (var e : m.entrySet())
                sb.append(i++ > 0 ? "," : "").append('"').append(e.getKey()).append("\":").append(json(e.getValue()));
            return sb.append("}").toString();
        }
        if (v instanceof List<?> l) {
            StringBuilder sb = new StringBuilder("[");
            int i = 0;
            for (Object o : l) sb.append(i++ > 0 ? "," : "").append(json(o));
            return sb.append("]").toString();
        }
        if (v instanceof String s) return "\"" + s + "\"";
        return v.toString();
    }

    public static void main(String[] args) {
        Map<String, Object> dbA = new LinkedHashMap<>(); // insertion order is preserved
        dbA.put("host", "localhost");
        dbA.put("port", 3306);
        Map<String, Object> a = new LinkedHashMap<>();
        a.put("db", dbA);
        a.put("debug", true);
        Map<String, Object> dbB = new LinkedHashMap<>();
        dbB.put("port", 5432);
        dbB.put("ssl", "on");
        Map<String, Object> b = new LinkedHashMap<>();
        b.put("db", dbB);
        System.out.println(json(merge(a, b)));
        System.out.println(json(replace(a, b)));
    }
}
Output
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

JavaScript v26.13.1

v26.13.1
const a = { db: { host: "localhost", port: 3306 }, debug: true };
const b = { db: { port: 5432, ssl: "on" } };
const isPlain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);

// merge_recursive analogue: same key with scalar values becomes an array of both, a first
function mergeRecursive(x, y) {
  const out = { ...x };
  for (const [k, v] of Object.entries(y)) {
    if (isPlain(out[k]) && isPlain(v)) out[k] = mergeRecursive(out[k], v);
    else if (k in out) out[k] = [out[k], v];
    else out[k] = v;
  }
  return out;
}

// replace_recursive analogue: b wins key by key, recursing into nested objects
function replaceRecursive(x, y) {
  const out = { ...x };
  for (const [k, v] of Object.entries(y)) {
    out[k] = isPlain(out[k]) && isPlain(v) ? replaceRecursive(out[k], v) : v;
  }
  return out;
}

console.log(JSON.stringify(mergeRecursive(a, b)));
console.log(JSON.stringify(replaceRecursive(a, b)));
Output
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

PHP v8.6.0

v8.6.0
$a = ["db" => ["host" => "localhost", "port" => 3306], "debug" => true];
$b = ["db" => ["port" => 5432, "ssl" => "on"]];
// merge_recursive: same string key with scalar values is merged into an ARRAY of both
echo json_encode(array_merge_recursive($a, $b)), "\n";
// replace_recursive: $b wins deep down, key by key
echo json_encode(array_replace_recursive($a, $b)), "\n";
Output
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

Python v3.15.2

v3.15.2
import json

a = {"db": {"host": "localhost", "port": 3306}, "debug": True}
b = {"db": {"port": 5432, "ssl": "on"}}

def merge_recursive(x, y):
    out = dict(x)
    for k, v in y.items():
        if k in out and isinstance(out[k], dict) and isinstance(v, dict):
            out[k] = merge_recursive(out[k], v)
        elif k in out:
            out[k] = [out[k], v]  # scalar collision becomes a list of both, a first
        else:
            out[k] = v
    return out

def replace_recursive(x, y):
    out = dict(x)
    for k, v in y.items():
        if k in out and isinstance(out[k], dict) and isinstance(v, dict):
            out[k] = replace_recursive(out[k], v)
        else:
            out[k] = v  # b wins deep down
    return out

print(json.dumps(merge_recursive(a, b), separators=(",", ":")))
print(json.dumps(replace_recursive(a, b), separators=(",", ":")))
Output
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

Rust v1.99.1

v1.99.1
use serde_json::{json, Value};

// merge_recursive analogue: same key with scalar values becomes an array of both, a first
fn merge_recursive(a: &Value, b: &Value) -> Value {
    if let (Some(x), Some(y)) = (a.as_object(), b.as_object()) {
        let mut out = x.clone();
        for (k, v) in y {
            match out.get(k) {
                Some(old) if old.is_object() && v.is_object() => {
                    out.insert(k.clone(), merge_recursive(old, v));
                }
                Some(old) => {
                    out.insert(k.clone(), json!([old, v]));
                }
                None => {
                    out.insert(k.clone(), v.clone());
                }
            }
        }
        return Value::Object(out);
    }
    b.clone()
}

// replace_recursive analogue: b wins key by key, recursing into nested objects
fn replace_recursive(a: &Value, b: &Value) -> Value {
    if let (Some(x), Some(y)) = (a.as_object(), b.as_object()) {
        let mut out = x.clone();
        for (k, v) in y {
            match out.get(k) {
                Some(old) if old.is_object() && v.is_object() => {
                    out.insert(k.clone(), replace_recursive(old, v));
                }
                _ => {
                    out.insert(k.clone(), v.clone()); // b wins
                }
            }
        }
        return Value::Object(out);
    }
    b.clone()
}

fn main() {
    let a = json!({"db": {"host": "localhost", "port": 3306}, "debug": true});
    let b = json!({"db": {"port": 5432, "ssl": "on"}});
    println!("{}", merge_recursive(&a, &b));
    println!("{}", replace_recursive(&a, &b));
}
Output
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

TypeScript v26.13.1

v26.13.1
type Obj = Record<string, unknown>;
const a: Obj = { db: { host: "localhost", port: 3306 }, debug: true };
const b: Obj = { db: { port: 5432, ssl: "on" } };
const isObj = (v: unknown): v is Obj => v !== null && typeof v === "object" && !Array.isArray(v);

// merge_recursive analogue: same key with scalar values becomes an array of both, a first
function mergeRecursive(x: Obj, y: Obj): Obj {
  const out: Obj = { ...x };
  for (const [k, v] of Object.entries(y)) {
    const old = out[k];
    if (isObj(old) && isObj(v)) out[k] = mergeRecursive(old, v);
    else if (k in out) out[k] = [old, v];
    else out[k] = v;
  }
  return out;
}

// replace_recursive analogue: b wins key by key, recursing into nested objects
function replaceRecursive(x: Obj, y: Obj): Obj {
  const out: Obj = { ...x };
  for (const [k, v] of Object.entries(y)) {
    const old = out[k];
    out[k] = isObj(old) && isObj(v) ? replaceRecursive(old, v) : v;
  }
  return out;
}

console.log(JSON.stringify(mergeRecursive(a, b)));
console.log(JSON.stringify(replaceRecursive(a, b)));
Output
{"db":{"host":"localhost","port":[3306,5432],"ssl":"on"},"debug":true}
{"db":{"host":"localhost","port":5432,"ssl":"on"},"debug":true}

Language differences

C: hand-written recursion over cJSON; scalar collisions wrap into a two-element array, a first; cJSON objects print in insertion order.

C++: hand-written recursion over nlohmann json; objects are std::map-backed, so sorted keys make the output naturally deterministic.

C#: no deep merge in the standard library; SortedDictionary sorts keys, keeping the output deterministic.

Go: hand-written recursion over maps; json.Marshal sorts map keys, so the output is deterministic.

Java: hand-written recursion plus a minimal serializer; LinkedHashMap preserves insertion order (Map.of order is not guaranteed, so the sample puts entries explicitly).

JavaScript: hand-written recursion; the '...' spread only merges one level deep — a common pitfall.

PHP: the core contrast — with merge_recursive, a scalar collision on the same string key merges into an array (port becomes [3306,5432]; repeatedly merging configs accumulates ever-longer arrays there, a classic accident source); replace_recursive overwrites deep down (b wins). Neither mutates the original arrays; merge_recursive renumbers integer keys like array_merge does, while replace_recursive keeps the original keys. Under merge_recursive, integer keys always append while string keys trigger the array aggregation.

Python: hand-written recursion; the '|' merge operator (3.9+) merges only one level deep — deep merging needs hand-written code.

Rust: hand-written recursion over serde_json Values; the validator's cargo mode enables preserve_order, matching PHP's insertion-order output.

TypeScript: same as JavaScript, with an Obj type annotation.