How to Use array_merge in PHP: Syntax and Examples
Use
array_merge in PHP to combine two or more arrays into one. It appends elements from later arrays to the first array, reindexing numeric keys and preserving string keys.Syntax
The array_merge function takes one or more arrays as arguments and returns a new array that combines all elements.
- array_merge(array1, array2, ...): Combines arrays in the order given.
- Numeric keys are reindexed starting from 0.
- String keys are preserved; if keys repeat, later values overwrite earlier ones.
php
array array_merge(array ...$arrays)
Example
This example shows how array_merge combines two arrays with numeric and string keys.
php
<?php $array1 = ["apple", "banana"]; $array2 = ["cherry", "date"]; $result = array_merge($array1, $array2); print_r($result); // Example with string keys $array3 = ["a" => "red", "b" => "green"]; $array4 = ["b" => "blue", "c" => "yellow"]; $result2 = array_merge($array3, $array4); print_r($result2); ?>
Output
Array
(
[0] => apple
[1] => banana
[2] => cherry
[3] => date
)
Array
(
[a] => red
[b] => blue
[c] => yellow
)
Common Pitfalls
Common mistakes when using array_merge include:
- Expecting numeric keys to be preserved (they are reindexed).
- Not realizing string keys with the same name get overwritten by later arrays.
- Using
+ (array union)operator instead, which behaves differently.
Here is a wrong and right way example:
php
<?php // Wrong: expecting numeric keys to stay the same $array1 = [1 => "one", 2 => "two"]; $array2 = [3 => "three"]; $result = array_merge($array1, $array2); print_r($result); // keys become 0,1,2 // Right: understand keys are reindexed // Use array_merge when you want a combined list ignoring original keys ?>
Output
Array
(
[0] => one
[1] => two
[2] => three
)
Quick Reference
Tips for using array_merge:
- Use it to combine arrays into one list.
- Numeric keys are reindexed starting at 0.
- String keys are preserved; later values overwrite earlier ones.
- For preserving keys without overwriting, consider
array_replaceor the+operator.
Key Takeaways
array_merge combines multiple arrays into one, reindexing numeric keys.
String keys are preserved and overwritten by later arrays if duplicated.
Use array_merge when you want a merged list ignoring original numeric keys.
Be careful: numeric keys do not stay the same after merging.
For preserving keys without overwriting, use alternatives like array_replace or + operator.