5.6. The + Operator

The + operator has a special meaning for arrays. It merges the elements from the array on the right into the array on the left. The keys of the arrays are important. If a key exists in the array on the left, it remains unchanged. Only elements from the array on the right with different keys merge into the array on the left. Listing 5.8 demonstrates this functionality.

Listing 5.8. Using the + with arrays
<?php
    //define a couple of arrays
    $a = array(
        0=>"Apple",
        2=>"Ball");
    $b = array(
        1=>"Cat",
        2=>"Dog");

    foreach(($a + $b) as $key=>$value)
    {
        print("$key: $value<br>\n");
    }
?>

Figure 5.1 shows that Listing 5.8 prints an array with three elements. The element indexed by 2 uses the value from a, not b.

Chapter 11 discusses ...

Get Core PHP Programming, Third Edition 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.