How to Merge Arrays in PHP


To merge arrays in PHP, the array_merge function is used with the following general syntax, as shown below:

array_merge($array1, $array2, ...)

$array2 is now appended to $array1

The array_merge function returns an array with the elements of two or more arrays into a single array.


So if we wanted to join together two arrays, $Male_students and $Female_students, we would do it with the following code.

$Male_students= array('John', 'Steve', 'Rick', 'Greg');
$Female_students= array('Lisa', 'Michelle', 'Elizabeth');
$All_students= array_merge($Male_students, $Female_students);
echo implode (', ', $All_students);

The implode function decides what separates the elements in the two arrays. In this example, we specify and separate them with a comma (, ).

Actual PHP Output

John, Steve, Rick, Greg, Lisa, Michelle, Elizabeth

Example Merging 3 Arrays

If you want to merge three arrays together, an example of PHP code to do so would be:

$Group1= array ('John', 'Michelle', 'Jeff');
$Group2= array('Steve', 'Elizabeth', 'Lisa');
$Group3= array('Rick', 'Greg', 'Kobe');
$Total_groups= array_merge ($Group1, $Group2, $Group3);
echo implode (', ', $Total_groups);

Actual PHP Output

John, Michelle, Jeff, Steve, Elizabeth, Lisa, Rick, Greg, Kobe

As can be seen, we can merge as many arrays as we want with the array_merge function.

HTML Comment Box is loading comments...