Storing Data in Arrays

Storing a value in an array will create the array if it didn’t already exist, but trying to retrieve a value from an array that hasn’t been defined yet won’t create the array. For example:

    // $addresses not defined before this point
    echo $addresses[0];                    // prints nothing
    echo $addresses;                       // prints nothing
    $addresses[0] = 'spam@cyberpromo.net';
    echo $addresses;                       // prints "Array"

Using simple assignment to initialize an array in your program leads to code like this:

    $addresses[0] = 'spam@cyberpromo.net';
    $addresses[1] = 'abuse@example.com';
    $addresses[2] = 'root@example.com';
    // ...

That’s an indexed array, with integer indexes beginning at 0. Here’s an associative array:

    $price['Gasket'] = 15.29;
    $price['Wheel']  = 75.25;
    $price['Tire']   = 50.00;
    // ...

An easier way to initialize an array is to use the array( ) construct, which builds an array from its arguments. This builds an indexed array, and the index values (starting at 0) are created automatically:

    $addresses = array('spam@cyberpromo.net', 'abuse@example.com',
                       'root@example.com');

To create an associative array with array( ), use the => symbol to separate indexes from values:

    $price = array('Gasket' => 15.29,
                   'Wheel'  => 75.25,
                   'Tire'   => 50.00);

Notice the use of whitespace and alignment. We could have bunched up the code, but it wouldn’t have been as easy to read:

    $price = array('Gasket'=>15.29,'Wheel'=>75.25,'Tire'=>50.00);

To construct an empty array, pass no arguments to array( ):

 $addresses = array( ); ...

Get Programming PHP, 2nd 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.