How to Merge Two Array Into a Single Using PHP

Last Updated on August 4, 2021 by Roshan Parihar

In this tutorial, learn how to combine or merge two array into a single array using PHP. The short answer is to use the array_combine() function PHP and pass two arrays as its argument with comma-separation.

You can also use the array_merge() function to combine the two array in PHP. Let’s find out the use of the methods with the examples given below here.

Methods 1: Using array_combine() to Combine Two Array in PHP

To combine the two array, you can use the PHP array_combine() function that takes the array variable as its arguments. You have to pass the two array variables in comma-separation. It creates the new array using the first array as its keys and the second array as its values.

Output

Array ( [English] => 69 [Maths] => 93 [Science] => 73 [Physics] => 71 )

The above example contains the two arrays in which the first array is the string array and the second is the numeric array. The output shows that the keys are string and the values are numeric.

Methods 2: Using array_merge() to Merge Two Array in PHP

If you want to merge two arrays, you have to use the array_merge() function that takes two arrays as its arguments. It merges the two array elements each item becomes the separate elements in the newly created array in PHP.

Output

Array ( [0] => English [1] => Maths [2] => Science [3] => Physics [4] => 69 [5] => 93 [6] => 73 [7] => 71 )

The new array elements are created with automatically assigned keys in sequence. The above output shows the new array with separate elements indexed automatically inside it.

Methods 3: Using Plus (+) Operator to Merge Arrays Using PHP

In addition to the above methods, you can also use the plus (+) operator to merge arrays in PHP. However, it requires associative array elements that contain elements with pre-assigned keys.

Output

Array ( [Cycle] => 2 [Bike] => 5 [Car] => 9 [Ricksaw] => 6 [Auto] => 11 [Motorcycle] => 13 )

The above example contains an element with the key “Car” for two times. However, the resulted array uses the first occurred element whether it comes for one time or more times.

You May Also Like to Read

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.