Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Recursive array_merge()

<?php

$array1 = ['x' => 1, 3 => 4, 't' => 8];
$array2 = ['x' => 2, 5 => 6,];
$array3 = ['x' => [3, 4, 5]];
$array4 = ['x' => [[4]]];
$arrays = [$array1, $array2, $array3, $array4];

print_r(array_merge_recursive(...$arrays));

array_merge_recursive() merges several arrays together, like its cousin array_merge(). The important difference here is where the recursive applies.

The operation is recursive because the string keys will be merged together into an array, whenever the same key is found multiple times. A new array is created: scalar values are added to this array, and arrays are merged with it. Single keys are kept intact and integer keys are reindexed, starting at 0.

Note that to avoid the merge of sub-arrays, one need to put it inside yet another array (see array).

See Also

PHP Features

Last updated: 10 September 2026