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:

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

Examples:

(1) Merge two arrays

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

(2) Merge multiple arrays

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

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

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

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.

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.

PHPCode 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

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.