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 class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 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.