How to Merge Arrays in PHP

PHP provides some built-in array functions which help to do array operation so easily. The array_merge() function is one of them. This article will explain how to merge two arrays with the array_merge() function.

Merge arrays in PHP

Merge arrays in PHP

PHP array_merge() function creates a new array merging two or more PHP arrays but the original arrays remain unchanged. The structure of a array_merge() function is given below…

$merged_array = array_merge($array1,$array2…….$arrayN);

The structure shows that the array_merge() function accepts two or more arrays as arguments and returns another array as a return value but does not change the original arrays. See below example…

 $web_lang = array("PHP","HTML","CSS");
 $apps_lang = array("C++","C#","Java");
 $com_lang = array_merge($web_lang,$apps_lang);
 echo "Merged array's elements : ";
 foreach($com_lang as $lang){
  echo $lang." ";
 echo " First array's elements : ";
 foreach($web_lang as $lang){
  echo $lang." ";
 echo " Second array's elements : ";
 foreach($apps_lang as $lang){
  echo $lang." ";


Merged array’s elements: PHP HTML CSS C++ C# Java
First array’s elements: PHP HTML CSS
Second array’s elements: C++ C# Java

The example shows that two arrays are merging with the array_merge() function but the original arrays are remaining unchanged. So, multiple PHP arrays can easily be merged  using the array_merge() function.

PHP array_combine() function

The array_combine() function helps to create a new array combining two arrays where one array elements will be indexes and another array elements will be elements of the new array. But the both arrays must have equal elements. See below example…


$fruits = array("Mango","Apple","Banana"); 
$colors = array("Green","Red","Yellow");
$fruit_color = array_combine($fruits,$colors); 

foreach($fruit_color as $key => $value){
   echo $key." is ".$value." ";

echo "The combined array is: ";




Mango is Green
Apple is Red
Banana is Yellow

The combined array is: Array ( [Mango] => Green [Apple] => Red [Banana] => Yellow )

The example shows that the array_combine() function returns an array which indexes are the first array elements and the values are the second array elements. So, two PHP arrays  can be combined using  the array_combine() function so easily.

Merging two arrays with array_merge() function and combining two arrays with array_combine() function have been explained in this article with example. If you feel any problem to understand this article, feel free to contact with me from Contact us page. I’ll try my best to stay with you. Creating PHP array dynamically with PHP range() function will be explained in next article. Spend some time to study the article and learn the strategy to create PHP array dynamically.

Leave a Comment

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