What is the method for merging arrays in PHP?

There are several ways to merge arrays in PHP.

  1. Using the + operator: The + operator can merge two arrays into a new array, if the two arrays have the same key names, the array that comes later will overwrite the array that comes before.
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("c" => "cat", "d" => "dog");
$result = $array1 + $array2;
print_r($result);

Result:

Array
(
    [a] => apple
    [b] => banana
    [c] => cat
    [d] => dog
)
  1. By using the array_merge function, multiple arrays can be combined into a new array. If there are duplicate keys, the values from the later arrays will overwrite the values from earlier arrays.
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("c" => "cat", "d" => "dog");
$result = array_merge($array1, $array2);
print_r($result);

Outcome:

Array
(
    [a] => apple
    [b] => banana
    [c] => cat
    [d] => dog
)
  1. Use the array_merge_recursive function: It can combine multiple arrays into a new array by merging values with the same key name in a recursive manner.
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("b" => "blue", "c" => "cat");
$result = array_merge_recursive($array1, $array2);
print_r($result);

As a result:

Array
(
    [a] => apple
    [b] => Array
        (
            [0] => banana
            [1] => blue
        )
    [c] => cat
)

It is important to note that in the above methods, the array merging involves appending the arrays at the end of the previous array. If you want to preserve elements with the same key names, you can use the array_replace or array_replace_recursive functions.

bannerAds