Mastering PHP’s array_merge: Combine Arrays Like a Pro

This article explains PHP's powerful array_merge() function, shows its syntax, and provides three clear examples—merging two indexed arrays, merging multiple arrays, and merging associative arrays—while illustrating the resulting output and key‑overriding behavior for practical data handling.

php Courses
php Courses
php Courses
Mastering PHP’s array_merge: Combine Arrays Like a Pro

PHP offers the array_merge() function to combine one or more arrays into a new array, returning the merged result. The syntax is straightforward: array_merge(array $array1 [, array $...]) : array.

Example 1: Merging two arrays

$array1 = array('apple', 'banana', 'orange');
$array2 = array('kiwi', 'melon', 'grape');
$result = array_merge($array1, $array2);
print_r($result);

The output shows all six elements from both arrays in order:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => kiwi
    [4] => melon
    [5] => grape
)

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);

The resulting array contains all elements from the three source arrays:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => kiwi
    [4] => melon
    [5] => grape
    [6] => strawberry
    [7] => pineapple
)

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);

When keys overlap, the later array's value overwrites the earlier one, so the merged array contains the name "Jane" while preserving the other keys:

Array
(
    [name] => Jane
    [age] => 25
    [email] => [email protected]
)

Conclusion

The array_merge() function is a concise and efficient way to combine both indexed and associative arrays in PHP, making data manipulation more flexible and convenient for backend development tasks.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPTutorialarray manipulationarray merge
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.