Current Location: Home> Latest Articles> PHP Tutorial: How to Efficiently Merge Multiple Arrays Using array_merge Function

PHP Tutorial: How to Efficiently Merge Multiple Arrays Using array_merge Function

M66 2025-06-07

Merging Multiple Arrays into One Using PHP's array_merge Function

In PHP development, it’s common to need to merge several arrays into a larger array for easier data processing. The built-in array_merge function is designed precisely for this purpose.

Basic Usage of array_merge Function

The array_merge function accepts multiple arrays as arguments and merges them into a new array. The basic syntax is:

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

Here, $array1 is the first required array to merge, followed by optional additional arrays.

Example: Merging a Fruits Array and a Vegetables Array

$fruits = array('apple', 'banana', 'cherry');
$vegetables = array('carrot', 'broccoli', 'cabbage');
<p>$combinedArray = array_merge($fruits, $vegetables);</p>
<p>print_r($combinedArray);<br>

The output is:

Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
    [3] => carrot
    [4] => broccoli
    [5] => cabbage
)

As shown, the elements from both arrays are merged sequentially into a new array.

Handling Key Conflicts in Associative Arrays

If the arrays contain string keys, array_merge overwrites values of matching keys from earlier arrays with values from later arrays. Numeric keys will be re-indexed to continuous numbers.

Example:

$array1 = array('a' => 'apple', 'b' => 'banana');
$array2 = array('b' => 'broccoli', 'c' => 'carrot');
<p>$combinedArray = array_merge($array1, $array2);</p>
<p>print_r($combinedArray);<br>

The output:

Array
(
    [a] => apple
    [b] => broccoli
    [c] => carrot
)

Here, the key 'b' is overwritten by the value from the second array.

Summary

array_merge is a highly useful function in PHP for simplifying the handling of multiple arrays. Understanding its behavior regarding key overwriting and index resetting helps you write more stable and efficient code.