PHP

Recursive Deep Merge

admin by @admin ADMIN
Jun 12, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Merge two associative arrays at any nesting depth — like array_merge_recursive, but later values OVERWRITE earlier ones at the leaf level instead of combining them into arrays. Perfect for config-file overrides.
PHP
Raw
<?php
function deepMerge(array $base, array $override): array {
    foreach ($override as $key => $val) {
        if (is_array($val) && isset($base[$key]) && is_array($base[$key]) && !array_is_list($val)) {
            $base[$key] = deepMerge($base[$key], $val);
        } else {
            $base[$key] = $val;
        }
    }
    return $base;
}

$defaults = ['db'=>['host'=>'localhost','port'=>3306],'debug'=>false];
$env      = ['db'=>['host'=>'prod.example.com'],'debug'=>true];

print_r(deepMerge($defaults, $env));
// db => [host => prod.example.com, port => 3306], debug => true
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.