Master PHP’s array_merge: Combine Arrays Effortlessly with Real Examples
This tutorial explains PHP’s array_merge function, showing its simple syntax and providing clear code examples for merging two arrays, multiple arrays, and associative arrays, while highlighting how keys are handled and why the function is essential for flexible data manipulation.
PHP offers many powerful functions for handling arrays, and array_merge() is one of the most useful. It merges one or more arrays into a new array and returns the result.
Syntax
array_merge ( array $array1 [, array $... ] ) : arrayExample 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
)The two original arrays are combined into a single array containing all elements in order.
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
)All three arrays are merged, preserving the order of elements from each source array.
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 keys overlap, the later array’s value overwrites the earlier one, so the final array keeps the last value for each duplicate key.
Conclusion
The array_merge() function is a concise and efficient way to combine both indexed and associative arrays in PHP. It simplifies data handling by allowing developers to merge any number of arrays, with clear behavior for duplicate keys.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
