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.
1 2 3 4 5 6 7 8 9 10 11 |
<?php //Declare an array in PHP $myarray1 = array("English", "Maths", "Science", "Physics"); $myarray2 = array(69, 93, 73, 71); //Combine two array as keys and values $newArr = array_combine($myarray1, $myarray2); //Print result print_r($newArr); ?> |
Output
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.
1 2 3 4 5 6 7 8 9 10 11 |
<?php //Declare an array in PHP $myarray1 = array("English", "Maths", "Science", "Physics"); $myarray2 = array(69, 93, 73, 71); //Combine two array as keys and values $newArr = array_merge($myarray1, $myarray2); //Print result print_r($newArr); ?> |
Output
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.
1 2 3 4 5 6 7 8 9 10 11 |
<?php //Declare an array in PHP $myarrayassoc1 = array("Cycle" => 2, "Bike" => 5, "Car" => 9); $myarrayassoc2 = array("Ricksaw" => 6, "Auto" => 11, "Motorcycle" => 13, "Car" => 16); //Combine two array as keys and values $newArr = $myarrayassoc1 + $myarrayassoc2; //Print result print_r($newArr); ?> |
Output
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