home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Programming PHPProgramming PHPSearch this book

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

$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( );

You can specify an initial key with => and then a list of values. The values are inserted into the array starting with that key, with subsequent values having sequential keys:

$days = array(1 => 'Monday',   'Tuesday', 'Wednesday',
                   'Thursday', 'Friday',  'Saturday', 'Sunday');
// 2 is Tuesday, 3 is Wednesday, etc.

If the initial index is a non-numeric string, subsequent indexes are integers beginning at 0. Thus, the following code is probably a mistake:

$whoops = array('Friday' => 'Black', 'Brown', 'Green');
// same as
$whoops = array('Friday' => 'Black', 0 => 'Brown', 1 => 'Green');


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.