How to Merge Two or More Arrays in PHP
Merging arrays is a frequent task for PHP developers, whether you’re combining configuration settings, aggregating data from multiple sources, or building complex data structures. This article walks you through every built‑in method, modern syntax, and custom technique you need to merge two or more arrays safely and efficiently.
Table of Contents
- Basic
array_merge()usage - Merging associative arrays
- Recursive merging with
array_merge_recursive() - The spread operator (
...) – PHP 7.4+ - Custom function for unique values
- Performance considerations
- Common pitfalls & how to avoid them
1. Basic array_merge() Usage
The most straightforward way to combine arrays in PHP is the array_merge() function. It appends the values of each subsequent array to the first one and reindexes numeric keys.
Example: Merging two indexed arrays
<?php
$fruits = ['apple', 'banana'];
$vegetables = ['carrot', 'lettuce'];
$combined = array_merge($fruits, $vegetables);
print_r($combined);
?>
Output:
Array
(
[0] => apple
[1] => banana
[2] => carrot
[3] => lettuce
)
Example: Merging more than two arrays
<?php
$a = [1, 2];
$b = [3, 4];
$c = [5, 6];
$all = array_merge($a, $b, $c);
print_r($all);
?>
2. Merging Associative Arrays
When dealing with associative arrays, array_merge() overwrites values that share the same string key. Numeric keys are still reindexed.
Example: Overwriting string keys
<?php
$defaults = ['color' => 'blue', 'size' => 'M'];
$user = ['size' => 'L', 'price' => 19.99];
$merged = array_merge($defaults, $user);
print_r($merged);
?>
Result:
Array
(
[color] => blue
[size] => L
[price] => 19.99
)
3. Recursive Merging with array_merge_recursive()
If you need to preserve values from both arrays when they share the same key, array_merge_recursive() creates an array of values for each duplicate key.
Example: Nested configuration arrays
<?php
$baseConfig = [
'db' => ['host' => 'localhost', 'port' => 3306],
'cache' => true
];
$envConfig = [
'db' => ['port' => 3307, 'username' => 'admin'],
'debug' => false
];
$merged = array_merge_recursive($baseConfig, $envConfig);
print_r($merged);
?>
Result:
Array
(
[db] => Array
(
[host] => localhost
[port] => Array
(
[0] => 3306
[1] => 3307
)
[username] => admin
)
[cache] => 1
[debug] =>
)
Notice how the duplicate port key becomes an array of both values. If you prefer the later value to overwrite the earlier one, you’ll need a custom solution (see section 5).
4. The Spread Operator (...) – PHP 7.4+
PHP 7.4 introduced the array spread operator, which provides a concise syntax for merging arrays, especially when the number of arrays is dynamic.
Example: Using the spread operator
<?php
$first = [1, 2];
$second = [3, 4];
$third = [5, 6];
$merged = [...$first, ...$second, ...$third];
print_r($merged);
?>
The result is identical to array_merge($first, $second, $third), but the syntax is shorter and works nicely with the array literal.
Dynamic merging with ...$array
<?php
$chunks = [
[10, 20],
[30, 40],
[50, 60]
];
$merged = [...$chunks[0], ...$chunks[1], ...$chunks[2]];
// Or using a loop:
$merged = [];
foreach ($chunks as $chunk) {
$merged = [...$merged, ...$chunk];
}
print_r($merged);
?>
5. Custom Function for Unique Values While Merging
Sometimes you want to merge arrays but keep only distinct values. array_unique() can be applied after merging, or you can write a helper that does both in one pass.
Simple post‑merge approach
<?php
$a = [1, 2, 3];
$b = [3, 4, 5];
$merged = array_unique(array_merge($a, $b));
print_r($merged);
?>
Optimized custom function (preserves order)
<?php
function mergeUnique(...$arrays): array {
$result = [];
foreach ($arrays as $array) {
foreach ($array as $value) {
if (!in_array($value, $result, true)) {
$result[] = $value;
}
}
}
return $result;
}
$unique = mergeUnique([1,2,3], [3,4,5], [5,6,7]);
print_r($unique);
?>
6. Performance Considerations
When merging large datasets, the choice of method can affect memory usage and execution time:
array_merge(): Fast for most cases, but it creates a new array each time, doubling memory usage temporarily.- Spread operator: Internally uses the same copy‑on‑write mechanism as
array_merge(), so performance is comparable. - Custom loops: Allow you to merge in‑place (e.g., using reference
&) and avoid intermediate copies, which can be beneficial for very large arrays.
For critical sections, benchmark with microtime(true) or tools like Xdebug to decide which approach fits your environment.
7. Common Pitfalls & How to Avoid Them
Numeric key reindexing
Both array_merge() and the spread operator reindex numeric keys. If you need to preserve original indexes, use the + (union) operator instead:
<?php
$a = [0 => 'zero', 2 => 'two'];
$b = [1 => 'one', 2 => 'duplicate'];
$union = $a + $b; // $b[2] is ignored because key 2 already exists in $a
print_r($union);
?>
Recursive merge creates nested arrays
As shown earlier, array_merge_recursive() can produce unexpected nested arrays. Use a custom recursive function that overwrites instead of nesting if that’s the desired behavior.
Mixing associative and indexed arrays
If you combine an indexed array with an associative one, the numeric keys from the indexed array will be reindexed, while string keys are kept. Plan your data structure accordingly.
Conclusion
Merging arrays in PHP is more than a one‑liner; it requires understanding how each function treats keys, values, and nesting. Use array_merge() for simple concatenation, array_merge_recursive() for deep merges (with caution), the spread operator for clean modern syntax, and custom helpers when you need uniqueness or in‑place performance. Armed with these techniques, you can handle any data‑combination scenario efficiently and reliably.
1 thought on “How to Merge Two or More Arrays in PHP”