How To Merge Two Array or Multiple Array in PHP

This PHP tutorial helps to understand array_merge() php function. I will merge two or multiple arrays and store them into another array.

This method is used to merge or combine one or multiple arrays into one single array. This function adds elements of one array to the end of the previous array and returns a single resulting array.

This is very simple and easy in PHP language using array_merge() function. The key will be overridden, if the two elements have the same string keys then the latter value will be overridden.

How To Combine Two array in PHP

To combine single or many arrays, PHP has an in-built method called array merge(). We only need to pass the source arrays and the name of the destination array variable. This function joins the items or values of two or more arrays to form a single array. The array_merge() method added one array element to the end of the previous array.

Also checkout other related tutorials,

The Syntax of array_merge() Method

The array_merge() function takes a list of arrays separated by commas as a parameter. This method returns a new array with merged values of arrays passed in the parameter.

Syntax
array array_merge($array1, $array2, ......, $arrayn)

PHP Array Merge With Same Key

The array merge method will override two elements with the same string keys by the latter value, as I mentioned at the start of the tutorial.

Source code –

<?php
$array1 = array(1, "fruit" => "banana", 2, "phpflow", 3);
$array2 = array("fruit" => "apple", "city" => "paris", 4, "c");
// Merging arrays together
$result = array_merge($array1, $array2);
print_r($result);
?>

The results –

Array
(
    [0] => 1
    [fruit] => apple
    [1] => 2
    [2] => phpflow
    [3] => 3
    [city] => paris
    [4] => 4
    [5] => c
)

Array Merge with integer keys

This function can also take arrays with integer keys as a parameter. The code>array merge()/code> method renumbers the key and appends it to the previous array. The key will begin at 0 and increment by 1 for subsequent entries.

Source code –

<?php
$array1 = array(1 => "apple", 2 => "banana", 4 => "Lychee");
// Merging arrays together
$result = array_merge($array1);
print_r($result);
?>

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => Lychee
)

Merge Two Array in PHP with integer keys

This example code helps to merge two multiple arrays using array_merge method.

Source code:

<?php
$array1 = array(0 => "apple", 2 => "banana", 3 => "Lychee", 5 => "avocado");
$array2 = array(0 => "red", 2 => "green", 4 => "yellow", 5 => "black");
// Merging arrays together
$result = array_merge($array1, $array2);
print_r($result);

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => Lychee
    [3] => avocado
    [4] => red
    [5] => green
    [6] => yellow
    [7] => black
)

Leave a Reply

Your email address will not be published. Required fields are marked *