Merge Arrays with the array_merge() Function in PHP

30-01-2023
PHP

Learn how to use the array_merge() function in PHP to combine arrays. See examples and sample code to help you use this function in your PHP projects. Whether you need to merge multiple arrays or add new elements to an existing array, array_merge() is the perfect tool to get the job done.

array_merge is a function in PHP that merges one or more arrays into a single array. The function takes one or more arrays as arguments and returns a new array that is the result of merging all the arrays.

Example 1:

<?php
$array1 = array("red", "green", "blue"); 
$array2 = array("yellow", "orange"); 
$array3 = array("purple", "pink"); 
$result = array_merge($array1, $array2, $array3); 
print_r($result);
?>

Output:

Array ( [0] => red [1] => green [2] => blue [3] => yellow [4] => orange [5] => purple [6] => pink )

Example 2:

<?php
$array1 = array("apple" => "red", "banana" => "yellow"); 
$array2 = array("orange" => "orange", "grape" => "purple"); 
$result = array_merge($array1, $array2); 
print_r($result);
?>

Output:

Array ( [apple] => red [banana] => yellow [orange] => orange [grape] => purple )