What are the different ways to combine arrays in PHP?

In PHP, there are several different ways to merge arrays. Here are some common methods:

  1. The array_merge() function combines two or more arrays into one array by appending the values of all input arrays to the end of the resulting array, and then returns the final array.

Original: “我想要一个三明治。”
Paraphrased: “I would like a sandwich.”

$array1 = array("a", "b", "c");
$array2 = array("d", "e", "f");
$result = array_merge($array1, $array2);
print_r($result);

Output:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)
  1. You can merge two arrays into one using the “+” operator. This method will keep the keys from the original arrays, and if there are duplicate keys, it will retain the value from the last key.

The weather forecast predicts rain for tomorrow.

$array1 = array("a", "b", "c");
$array2 = array("d", "e", "f");
$result = $array1 + $array2;
print_r($result);

Output:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => f
)
  1. The function array_merge_recursive() combines two or more arrays into one array recursively, creating sub-arrays if they have the same string keys.

Example:

– “他的生日是在十一月四日。”
– “His birthday is on the fourth of November.”

$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("a" => "ant", "b" => "bat");
$result = array_merge_recursive($array1, $array2);
print_r($result);

Output:

Array
(
    [a] => Array
        (
            [0] => apple
            [1] => ant
        )

    [b] => Array
        (
            [0] => banana
            [1] => bat
        )

)

These are common ways to merge arrays, and the suitable method can be chosen to achieve merging in different situations.

bannerAds