Merge Multiple Arrays Into one Array Using PHP array_merge() Function

By Faruque Ahamed Mollick

In this post, we are going to see an amazing tutorial. We are going to plays with multiple arrays. I hope you are going to enjoy this tutorial.

Suppose we have two or more than two arrays and we need to combine it and make one array. How to do it? is it really possible?

Of course, we can merge one or two or multiple arrays into one single array easily using the PHP array_merge() function. We can take as many arrays as we want and transform it into one array. Now we are going to see the usage of PHP array_merge() function.

How to convert JSON string to PHP Array?



Search for restaurants using Zomato API in PHP

Below is the syntax of using the array_merge function:

array_merge(array1, array2, array3, array4….)

And as many as we can.

Now we are going to see a simple example of merging two arrays in PHP. For this, we are going to take two arrays.

The first array is $$car_owners_id which is given below:

$car_owners_id = array(
  'Michel'=>1023,
  'Rajesh'=>1024,
  'Robin'=>1025
);

And the second array is $bike_owners_id which is given below:

$bike_owners_id = array(
   'Mike'=>2545,
   'Uday'=>2546,
   'Ahmed'=>2547,
   'Yousuf'=>2548
);

Now we are going to combine the above two arrays into one array. We can easily do it by the code that is given below:

array_merge($car_owners_id, $bike_owners_id)

For better understanding let’s print it inside HTML pre tag:

echo "<pre>"; print_r( array_merge($car_owners_id, $bike_owners_id) ); echo "</pre>";

Now if you see the output, you can a single array that contains all the index and its value of both the two arrays just like we can see below:

Array
(
    [Michel] => 1023
    [Rajesh] => 1024
    [Robin] => 1025
    [Mike] => 2545
    [Uday] => 2546
    [Ahmed] => 2547
    [Yousuf] => 2548
)

So we have just merged two arrays and create a new one which contains all the keys and it’s value. is that not so easy? What do you think?

How to create JSON formatted text in PHP

How to parse JSON file in PHP?

Note that, if two or more than two array elements have the same key, the last one will always override the other.

Also,  If we assign only one array to the array_merge() PHP function as the parameter, and the keys are integers, the function will then return a new array with integer keys starting at 0 and increases by 1 for each value. For example:

$colors = array(3=>"blue",4=>"red");
print_r(array_merge($colors ));

The output of the above program will be:

Array ( [0] => blue[1] => red)


 

Leave a Reply

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