Backend Development 3 min read

Understanding and Using PHP's array_merge() Function

This article explains PHP's array_merge() function, its syntax, provides multiple code examples for merging two or more arrays, and highlights key considerations such as key overwriting when duplicate keys are present in PHP.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding and Using PHP's array_merge() Function

What is array_merge() function?

array_merge() is a PHP function that merges one or more arrays into a new array, preserving order and returning the combined result.

Usage of array_merge()

Function syntax:

<code>array array_merge ( array $array1 [, array $... ] )</code>

Examples:

(1) Merge two arrays

<code>$array1 = array("red", "green");
$array2 = array("blue", "yellow");
$result = array_merge($array1, $array2);
// Output: Array ( [0] => red [1] => green [2] => blue [3] => yellow )</code>

(2) Merge multiple arrays

<code>$array1 = array("red", "green");
$array2 = array("blue", "yellow");
$array3 = array("orange", "purple");
$result = array_merge($array1, $array2, $array3);
// Output: Array ( [0] => red [1] => green [2] => blue [3] => yellow [4] => orange [5] => purple )</code>

Note: When arrays have identical keys, later arrays overwrite earlier values.

<code>$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
// Output: Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 )</code>

Summary

array_merge() is a practical PHP function for merging arrays; it combines one or more arrays into a new one, with later values overriding earlier ones for duplicate keys.

BackendPHPcode examplesarraysarray_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.