CodeBlanks Logo Icon CodeBlanks

Merging with array_merge()

PHP course · Beginner · Lesson 61/116

Learn to merge two arrays into one with array_merge().

Merging with array_merge()

array_merge() combines two or more arrays into one. Think of placing two arrays end to end. array_merge($a, $b) lists the elements of $a first, then the elements of $b.

For arrays with numeric indexes, the elements are re-indexed: 0, 1, 2, ... in order. The merged array has a total length equal to the sum of the two arrays.

Numeric and string keys

array_merge() behaves differently with numeric and string indexes. Numeric indexes are always renumbered; so [5 => "a"] and [7 => "b"] merge into [0 => "a", 1 => "b"].

String keys are overwritten: if the same key exists, the value from the last array wins. For example, array_merge(["name" => "Alex"], ["name" => "Sam"]) yields ["name" => "Sam"]; the first "Alex" is lost. Watch out for matching keys.

Exercise Merge two lists

Define two arrays: $letters = ["A", "B"] and $more = ["C", "D"]. Use array_merge() to combine them into $all. Then walk through them with foreach ($all as $letter) and print each element on its own line with echo $letter . "\n".

Show example solution
First merge with $all = array_merge($letters, $more);. Then loop with foreach ($all as $letter) { echo $letter . "\n"; } and print.
Example solution:
<?php
$letters = ["A", "B"];
$more = ["C", "D"];
// Merge two lists and print them
$all = array_merge($letters, $more);
foreach ($all as $letter) {
    echo $letter . "\n";
}

Test yourself

  1. What does array_merge do?

    • Sorts an array
    • Merges two arrays
    • Removes an element
    • Reverses an array
    Show answer

    Merges two arrays — Correct. array_merge combines two or more arrays into one.

  2. Complete merging two arrays

    $a = [1, 2];
    $b = [3, 4];
    $merged = ____($a, $b);
    print_r($merged);
    Show answer
    $a = [1, 2];
    $b = [3, 4];
    $merged = array_merge($a, $b);
    print_r($merged);
  3. Match each case to its result

    Numeric indexes
    Renumbered
    String keys
    Last value wins
    Merging empty array
    Other array returns
  4. What is the output of the code below?

    $a = [1, 2];
    $b = [3, 4];
    print_r(array_merge($a, $b));
    • [1, 2, 3, 4]
    • [1, 2]
    • [3, 4]
    • [3, 4, 1, 2]
    Show answer

    [1, 2, 3, 4] — Correct. array_merge lists $a's elements first, then $b's.

All lessons in Beginner