PHP Merge Two Arrays (array_merge)

This guide will show you how to merge two arrays in PHP. This is useful when you have two arrays of data that you would like to become one. For example, you might have an array that has User 1 favorite movies and another with User 2. By merging the arrays we will know what are the favorite movies of the two combined.

First we need to establish two arrays. Below I have $array1 which has the first three letters of the alphabet. $array2 has the next three letters of the alphabet.

#array1
$array1 = array("a", "b", "c");
#array2
$array2 = array("d", "e", "f");

Next we will use the array_merge function and pass it our two arrays, $array1 and $array2. I am saving the combined array as a new array called $merge_array.

#merge the arrays together
$merge_array = array_merge($array1,$array2);
#quick validation
print_r($merge_array);

Now that the arrays have been merged, I print the output to show what our merged array looks like. As you can see $merge_array has the first six letters of the alphabet. This is a combination of $array1 and $array2.

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)

As you can see it was easy to merge two arrays using PHP. The full code might look something like below when we put it all together. There are many different use cases for merging arrays. If you are having troubles or want to share what projects you work on that requires merging arrays, please drop a comment below!

#array1
$array1 = array("a", "b", "c");
#array2
$array2 = array("d", "e", "f");
#merge the arrays together
$merge_array = array_merge($array1,$array2);
#quick validation
print_r($merge_array);

If you would like to suggest a new article or video to be released, please reach out via the Contact Page. I look forward to hearing your feedback and providing content that is helpful for you!

Leave a Comment