How To Merge Two Arrays In Php

In this blog post, we are going to discuss how to merge two arrays in PHP. Array merging is a common requirement when working with data in PHP. You might have two different sets of data that you want to combine into a single array for easier manipulation and processing.

Merging Arrays with array_merge()

PHP provides a built-in function called array_merge() that can be used to merge two or more arrays together. This function takes multiple arrays as arguments and returns a single array containing all the elements from the input arrays.

$array1 = array("red", "green", "blue");
$array2 = array("yellow", "orange", "purple");

$mergedArray = array_merge($array1, $array2);
print_r($mergedArray);

The output of the above code will be:

Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => yellow
    [4] => orange
    [5] => purple
)

The array_merge() function can also be used to merge associative arrays. If the input arrays have the same keys, the values from the later arrays will overwrite the values from the previous arrays.

$array1 = array("color1" => "red", "color2" => "green", "color3" => "blue");
$array2 = array("color2" => "yellow", "color4" => "orange", "color5" => "purple");

$mergedArray = array_merge($array1, $array2);
print_r($mergedArray);

The output of the above code will be:

Array
(
    [color1] => red
    [color2] => yellow
    [color3] => blue
    [color4] => orange
    [color5] => purple
)

Merging Arrays with the + Operator

Alternatively, you can use the + operator to merge two associative arrays. This method is also known as a “union” operation. When using this method, if the input arrays have the same keys, the values from the first array will be preserved, and the values from the second array will be ignored.

$array1 = array("color1" => "red", "color2" => "green", "color3" => "blue");
$array2 = array("color2" => "yellow", "color4" => "orange", "color5" => "purple");

$mergedArray = $array1 + $array2;
print_r($mergedArray);

The output of the above code will be:

Array
(
    [color1] => red
    [color2] => green
    [color3] => blue
    [color4] => orange
    [color5] => purple
)

In conclusion, merging arrays in PHP can be easily achieved using either the array_merge() function or the + operator. The choice between these two methods depends on your specific requirements and how you want to handle duplicate keys in the arrays.