php
18 lines · 6 steps
Recursively merging nested config arrays in PHP
A recursive helper that merges override values into defaults, descending only into nested associative arrays.
Explained by
highlit
1function deepMerge(array $defaults, array $overrides): array
2{
3 foreach ($overrides as $key => $value) {
4 if (
5 is_array($value)
6 && isset($defaults[$key])
7 && is_array($defaults[$key])
8 && !array_is_list($value)
9 && !array_is_list($defaults[$key])
10 ) {
11 $defaults[$key] = deepMerge($defaults[$key], $value);
12 } else {
13 $defaults[$key] = $value;
14 }
15 }
16
17 return $defaults;
18}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Recursion lets you merge arbitrarily deep structures with a single small function.
- 2Distinguishing lists from associative arrays prevents accidentally merging sequential data element-by-element.
- 3Passing arrays by value and returning the result keeps the merge free of side effects.
Related explainers
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
python
import os from datetime import timedelta
Class-based config in a Flask app factory
configuration
app-factory
inheritance
Intermediate
7 steps
php
<?php namespace App\Services;
Batch image resizing with PHP GD
image-processing
constructor-promotion
match-expression
Intermediate
10 steps
php
<?php namespace App\Cache;
A content-hashed fragment cache in PHP
caching
content-hashing
atomic-writes
Intermediate
10 steps
php
<?php namespace App\View\Composers;
How a Laravel view composer feeds the navigation
view-composer
caching
dependency-injection
Intermediate
5 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/recursively-merging-nested-config-arrays-in-php-explained-php-9ee4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.