Using PHP array_merge() to Combine Arrays: Syntax, Examples, and Tips
This article explains the PHP array_merge() function, covering its simple syntax, how it merges multiple indexed and associative arrays, and provides three practical code examples demonstrating merging two arrays, multiple arrays, and associative arrays with key overwriting.
PHP provides many powerful functions for handling arrays, and one of the most useful is array_merge() , which merges multiple arrays into a new array and returns the result.
The syntax of array_merge() is straightforward:
array_merge ( array $array1 [, array $... ] ) : arrayThe function accepts any number of array arguments and returns a single combined array.
Example 1: Merging Two Arrays
$array1 = array('apple', 'banana', 'orange');
$array2 = array('kiwi', 'melon', 'grape');
$result = array_merge($array1, $array2);
print_r($result);Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
[3] => kiwi
[4] => melon
[5] => grape
)This demonstrates that the two original arrays are combined, preserving the order of elements.
Example 2: Merging Multiple Arrays
$array1 = array('apple', 'banana', 'orange');
$array2 = array('kiwi', 'melon', 'grape');
$array3 = array('strawberry', 'pineapple');
$result = array_merge($array1, $array2, $array3);
print_r($result);Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
[3] => kiwi
[4] => melon
[5] => grape
[6] => strawberry
[7] => pineapple
)The function can handle any number of arrays, appending each subsequent array's elements to the result.
Example 3: Merging Associative Arrays
$array1 = array('name' => 'John', 'age' => 25);
$array2 = array('name' => 'Jane', 'email' => '[email protected]');
$result = array_merge($array1, $array2);
print_r($result);Output:
Array
(
[name] => Jane
[age] => 25
[email] => [email protected]
)When merging associative arrays, duplicate keys are overwritten by the later array's values, as shown with the 'name' key.
Summary
The array_merge() function is a versatile tool for combining both indexed and associative arrays in PHP. It offers a concise and efficient way to merge data structures, making array manipulation more flexible in real‑world applications.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.