How to Merge Two Arrays in PHP: Simple Guide
In PHP, you can merge two arrays using the
array_merge() function which combines elements from both arrays. Alternatively, you can use the + operator to merge arrays while preserving keys from the first array.Syntax
The main ways to merge arrays in PHP are:
array_merge(array1, array2, ...): Combines arrays by appending elements and reindexing numeric keys.array1 + array2: Adds elements fromarray2toarray1only if keys do not exist inarray1.
php
<?php // Using array_merge $result = array_merge($array1, $array2); // Using + operator $result = $array1 + $array2; ?>
Example
This example shows how array_merge() and the + operator merge two arrays differently.
php
<?php $array1 = ["a" => "apple", "b" => "banana"]; $array2 = ["b" => "blueberry", "c" => "cherry"]; // Merge with array_merge $merged = array_merge($array1, $array2); print_r($merged); // Merge with + operator $union = $array1 + $array2; print_r($union); ?>
Output
Array
(
[a] => apple
[b] => blueberry
[c] => cherry
)
Array
(
[a] => apple
[b] => banana
[c] => cherry
)
Common Pitfalls
Common mistakes when merging arrays include:
- Expecting
array_merge()to preserve keys for numeric arrays; it reindexes numeric keys. - Using the
+operator and expecting it to overwrite keys; it does not overwrite existing keys in the first array. - Not understanding that
array_merge()appends values, which can duplicate keys if numeric.
php
<?php // Wrong: expecting + to overwrite keys $array1 = [1 => 'one', 2 => 'two']; $array2 = [2 => 'deux', 3 => 'trois']; $result = $array1 + $array2; print_r($result); // key 2 stays 'two', not 'deux' // Right: use array_merge to overwrite $result = array_merge($array1, $array2); print_r($result); // keys reindexed, values appended ?>
Output
Array
(
[1] => one
[2] => two
[3] => trois
)
Array
(
[0] => one
[1] => two
[2] => deux
[3] => trois
)
Quick Reference
Summary of array merging methods:
| Method | Behavior | Key Handling |
|---|---|---|
| array_merge() | Appends arrays, reindexes numeric keys | Numeric keys reindexed, string keys overwritten |
| + operator | Adds elements from second array only if key not in first | Preserves keys, no overwriting |
Key Takeaways
Use
array_merge() to combine arrays and overwrite string keys, but numeric keys get reindexed.Use the
+ operator to merge arrays without overwriting existing keys in the first array.Understand how keys are handled to avoid unexpected results when merging arrays.
Test your merge method with your specific arrays to ensure it behaves as you expect.