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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access