e Learning

How to Join Two Arrays in PHP using array_merge Function

In PHP array_merge() function is used to merge two or more arrays together.

Example : use array_merge function two merge two arrays in PHP

In This Example we have two PHP arrays, $color1 and $color2. And we Combined $color1 and $color2 using php array_merge function.

$color1=array('Red','Green','Blue');
$color2=array('White','Black');
$result=array_merge($color1,$color2);
print_r($result);
Array ( [0] => Red [1] => Green [2] => Blue [3] => White [4] => Black ) 

Example 2

$array_one=array('country1'=>'USA','country2'=>'UK');
$array_two=array('country1'=>'Canada','country3'=>'France');
$array_three=array('country4'=>'Spain','country5'=>'China');
$result=array_merge($array_one,$array_two,$array_three);
print_r($result);
Array ( [country1] => Canada [country2] => UK [country3] => France [country4] => Spain [country5] => China ) 

In the above Example we join three PHP arrays together. Also notice that both $array_one and array_two have the same array key country1. So when PHP joins three arrays together country1 key of the array_two will override the country1 key of the $array_one.