Backend Development 4 min read

Using PHP array_merge() to Combine Arrays

This article explains the PHP array_merge() function, its syntax, and provides clear examples of merging indexed and associative arrays, demonstrating how multiple arrays can be combined into a new array with key overwriting behavior for duplicates.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP array_merge() to Combine Arrays

PHP provides many powerful functions for handling arrays, and array_merge() is one of the most useful, allowing multiple arrays to be combined into a new array.

The syntax of array_merge() is straightforward:

array_merge ( array $array1 [, array $... ] ) : array

The function accepts any number of array arguments and returns the merged result.

Example 1 merges two indexed arrays:

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

The output shows all elements from both arrays in order.

Example 2 merges three arrays, demonstrating that array_merge() can handle more than two inputs.

$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.

Example 3 merges associative arrays; when keys overlap, the later array's value overwrites the earlier one.

$array1 = array('name' => 'John', 'age' => 25);
$array2 = array('name' => 'Jane', 'email' => '[email protected]');
$result = array_merge($array1, $array2);
print_r($result);

The output shows that the 'name' key from the second array replaces the first, while other keys are retained.

In summary, array_merge() is a concise and efficient way to combine both indexed and associative arrays in PHP, making data manipulation more flexible.

Backend DevelopmentPHPCode Examplearraysarray_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

login 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.