Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page