PHP - Merging two or more arrays using array_merge()

In this article, we will learn how to append arrays in PHP? In order to do it, we will use a built in PHP function called, `array_merge()` which expects parameters in array data type and returns the new array combining the parameters. By Abhishek Pathak Last updated : December 19, 2023

Prerequisites

To understand this example, you should have the basic knowledge of the following PHP topics:

In PHP we require to work a lot on arrays and perform operations on it. In a program there are various arrays and sometimes we need to merge the arrays. If you have been in such a situation, PHP in-built function is there to save you and combine the arrays into a single array.

Appending/merging of two or more arrays

In order to do it, we will use a built in PHP function called, array_merge() function which expects parameters in array data type and returns the new array combining the parameters: array_merge($array1, $array2)

The order of parameters depend the order of elements in new array. The first parameter will be appended first and then second and so on. To understand it better, let's take a look at the example,

PHP code to merge two or more arrays

<?php
// Define two arrays
$fruits = array("Apple", "Orange");
$vegetables = array("Cabbage", "Brinjal");

// Merging the array
$garden = array_merge($fruits, $vegetables);

// Since garden is array, to show it we use for loop
for ($i = 0; $i < count($garden); $i++) {
    echo $garden[$i] . " ";
}
?>

Output

Apple Orange Cabbage Brinjal

Explanation

First we define two arrays named, fruits and vegatables each containing elements in them. Then we use the built in array_merge function that merges the two array in the order and store in the garden array.

To access the elements of this new array we have to use the loop to print each of the elements of garden array. We begin loop from 0 index to length of the array, which we get through count() function. Then we echo the each element of the array using the index, $garden[i].

In the output we get the final array combination of multiple arrays in the order they were specified in the arrays_merge() function. If you like the article, share your thoughts in the comments below.

PHP Array Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.