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