How to merge arrays in PHP?

How to merge arrays in PHP?

The array_merge() function merges one or more arrays into one array. The array_merge() merges one or more arrays provided as input and provides a new array as output. In the array merge, the second array values are added to the end of the first array and thus they both get merge into one and provide the new array.

Sometimes when we work on the project, we require to merge the two array into one. For example we have two arrays and we want both to merge into one so that we can perform some activity on the basis of that newly formed array.

Syntax

array array_merge( $arr1, $arr2, $arr3... )

Parameters: The array_merge() function accepts one or more input array and merges them into a single resulting array.

Let’s understand the array_merge() function with the following example.

<!DOCTYPE html>
<html>
<body>

<?php
$array1=array("orange","pink");
$array2=array("red","green");
print_r(array_merge($array1,$array2));
?>

</body>
</html>

Output

Array
(
    [0] => orange
    [1] => pink
    [2] => red
    [3] => green
)

In the above post, we can see, we have array $array1 and $array2 with values. When we pass these two arrays in array_merge() function, the new array will be returned with all the values from $array1 and $array2. Here we have $array1 in the first place so the whenever the new array comes after 1st that will be added in last of the array.

Conclusion:

We have got to know how to use array_merge() function in the PHP. It is very easy to use function, you only need to pass the arrays in the function and you will get back the new array as output.

You can also check How to remove empty values from an array in PHP.

Hope it helped you. If you have any queries and doubt about the article, please comment us below, we would love to help you.

Spread the love