C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » PHP

Appending/merging of two arrays in PHP

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.
Submitted by Abhishek Pathak, on November 09, 2017

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.

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: 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,

Code

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

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.





Sponsored Links




COMMENTS