Name

array_merge()

Synopsis

    array array_merge ( array arr1 [, array arr2 [, array ...]] )

The array_merge() function combines two or more arrays by renumbering numerical indexes and overwriting string indexes, if there is a clash.

    $toppings1 = array("Pepperoni", "Cheese", "Anchovies", "Tomatoes");
    $toppings2 = array("Ham", "Cheese", "Peppers");
    $both_toppings = array_merge($toppings1, $toppings2);

    var_dump($both_toppings);
    // prints: array(7) { [0]=> string(9) "Pepperoni" [1]=>
    // string(6) "Cheese" [2]=> string(9) "Anchovies" [3]=>
    // string(8) "Tomatoes" [4]=> string(3) "Ham" [5]=>
    // string(6) "Cheese" [6]=> string(7) "Peppers" }

Tip

The + operator in PHP is overloaded so that you can use it to merge arrays, e.g., $array3 = $array1 + $array2. But if it finds any keys in the second array that clash with the keys in the first array, they will be skipped.

The array_merge() will try to retain array keys when possible. For example, if you are merging two arrays that have no duplicate keys, all the keys will be retained. However, if there are key clashes, array_merge() will use the clashing key from the last array that contains it. For example:

    $arr1 = array("Paul"=>25, "Ildiko"=>38, "Nick"=>27);
    $arr2 = array("Ildiko"=>27, "Paul"=>38);

    print "Merge:\n";
    var_dump(array_merge($arr1, $arr2));
    // Values 27 and 38 clash, so their keys from $arr2 are used.
    // So, output is Paul (38), Ildiko (27), and Nick (27).

You can merge several arrays simultaneously by providing more parameters to the function. ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.