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; // prints nothing echo $addresses; // prints nothing $addresses = 'email@example.com'; echo $addresses; // prints "Array"
Using simple assignment to initialize an array in your program leads to code like this:
$addresses = 'firstname.lastname@example.org'; $addresses = 'email@example.com'; $addresses = 'firstname.lastname@example.org'; // ...
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('email@example.com', 'firstname.lastname@example.org', 'email@example.com');
To create an associative array with
array( ), use the
=> symbol to separate indexes from
$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
$addresses = array( ); ...