When working with PHP arrays, you may need to combine information from several sources into one collection. For example, you might want to join product lists, combine user preferences, or apply custom settings over application defaults.
The array_merge() function combines multiple arrays while applying specific rules to numeric and string keys.
What Is array_merge() in PHP?
The array_merge() function combines the elements of one or more arrays into a new array.
Its syntax is:
array_merge(array ...$arrays): array
You can provide multiple arrays as arguments. PHP processes them in the order they are supplied.
Two important rules determine the result:
- Numeric keys: Values are appended and assigned new sequential integer keys starting at zero.
- String keys: If the same key appears more than once, the value from the later array replaces the earlier value.
The function returns a new array and leaves the original arrays unchanged.
Example 1: Combining Indexed Arrays
Let's combine two lists of programming languages.
<?php
$backend = ["PHP", "Python"];
$frontend = ["JavaScript", "TypeScript"];
$languages = array_merge(
$backend,
$frontend
);
print_r($languages);
Output:
Array
(
[0] => PHP
[1] => Python
[2] => JavaScript
[3] => TypeScript
)
PHP appends the second array's elements after the first array's elements.
The same rule applies when the original numeric keys are different. For example, keys 5 and 10 will not be preserved; the merged result receives new numeric indexes.
Example 2: Merging Associative Arrays
Associative arrays behave differently because their string keys are preserved.
<?php
$defaults = [
"theme" => "light",
"language" => "en"
];
$preferences = [
"theme" => "dark",
"timezone" => "UTC"
];
$settings = array_merge(
$defaults,
$preferences
);
print_r($settings);
Output:
Array
(
[theme] => dark
[language] => en
[timezone] => UTC
)
The value of theme changes to dark because the second array contains the same string key.
The language entry remains unchanged, while timezone is added.
Remember: Later arrays have priority when string keys overlap.
Example 3: Merging More Than Two Arrays
You can combine several arrays in a single call.
<?php
$first = ["PHP"];
$second = ["Python"];
$third = ["Go", "Rust"];
$result = array_merge(
$first,
$second,
$third
);
print_r($result);
Output:
Array
(
[0] => PHP
[1] => Python
[2] => Go
[3] => Rust
)
Since PHP 7.4, calling array_merge() without any arguments also works and returns an empty array.
Practical Example: Combining Application Settings
Imagine an application with three configuration levels: default settings, environment settings, and user preferences.
Each level should override matching settings from the previous level.
Create a file named merge-settings.php:
<?php
declare(strict_types=1);
// Application defaults.
$defaults = [
"theme" => "light",
"language" => "en",
"items_per_page" => 10
];
// Environment-specific settings.
$environment = [
"items_per_page" => 25
];
// User preferences.
$userPreferences = [
"theme" => "dark"
];
// Combine settings in priority order.
$settings = array_merge(
$defaults,
$environment,
$userPreferences
);
// Display the final configuration.
echo "<h2>Application Settings</h2>";
echo "<ul>";
foreach ($settings as $key => $value) {
$message = $key . ": " . (string) $value;
echo "<li>" . htmlspecialchars(
$message,
ENT_QUOTES,
"UTF-8"
) . "</li>";
}
echo "</ul>";
Browser output:
Application Settings
theme: dark
language: en
items_per_page: 25
The final configuration combines all three sources. Environment settings override matching defaults, and user preferences take priority over both.
This approach is useful for configuration management, default options, and customizable application behavior.
Does array_merge() Merge Nested Arrays?
No. array_merge() performs a shallow merge.
If two arrays contain the same string key and its value is another array, the later nested array replaces the earlier one.
<?php
$defaults = [
"database" => [
"host" => "localhost",
"port" => 3306
]
];
$custom = [
"database" => [
"port" => 3307
]
];
$result = array_merge($defaults, $custom);
print_r($result["database"]);
Output:
Array
(
[port] => 3307
)
The original host entry is lost from the merged result.
For nested data, consider array_replace_recursive() or an explicitly defined merging strategy. array_merge_recursive() also exists, but its handling of duplicate keys differs, so it is not always an appropriate replacement.
array_merge() vs the + Operator vs Array Unpacking
PHP offers several ways to combine arrays, but they don't all behave identically.
| Method | Behavior |
|---|---|
array_merge($a, $b) |
Appends numeric-keyed values and lets later string-keyed values overwrite earlier ones. |
$a + $b |
Preserves existing keys and prioritizes values from the left array. |
[...$a, ...$b] |
Uses array unpacking, with merging behavior equivalent to array_merge() in PHP 8.1+. |
String-keyed array unpacking requires PHP 8.1 or later. Earlier versions support unpacking arrays with integer keys only.
Use the array union operator (+) when preserving original numeric keys or prioritizing entries from the first array is important.
Common Mistakes
- Expecting numeric keys to remain unchanged:
array_merge()renumbers them. - Ignoring duplicate string keys: Values from later arrays overwrite earlier ones.
- Expecting recursive merging: Nested arrays under matching string keys are replaced.
- Confusing merging with combining keys and values: Use
array_combine()when one array should provide keys and another should provide values.
Key Takeaways
array_merge()combines one or more arrays into a new array.- Numeric-keyed elements are appended and reindexed.
- String keys are preserved, with later values taking priority.
- Input arrays remain unchanged.
- The function performs a shallow merge, not a recursive one.
- It is useful for combining lists, configuration settings, and structured application data.
The array_merge() function is a straightforward way to combine PHP arrays. Understanding how it treats numeric keys, string keys, and nested values helps you choose the correct merging approach and avoid unexpected results.
For additional details, see the official PHP array_merge() documentation.