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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Recursion lets you merge arbitrarily deep structures with a single small function.
  2. 2Distinguishing lists from associative arrays prevents accidentally merging sequential data element-by-element.
  3. 3Passing arrays by value and returning the result keeps the merge free of side effects.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Recursively merging nested config arrays in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code