05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

That’s an indexed array, with integer indexes beginning at 0. Here’s an associative<br />

array:<br />

$price['Gasket'] = 15.29;<br />

$price['Wheel'] = 75.25;<br />

$price['Tire'] = 50.00;<br />

// ...<br />

An easier way to initialize an array is to use the array( ) construct, which builds an<br />

array from its arguments:<br />

$addresses = array('spam@cyberpromo.net', 'abuse@example.com',<br />

'root@example.com');<br />

To create an associative array with array( ), use the => symbol to separate indexes<br />

from values:<br />

$price = array('Gasket' => 15.29,<br />

'Wheel' => 75.25,<br />

'Tire' => 50.00);<br />

Notice the use of whitespace and alignment. We could have bunched up the code,<br />

but it wouldn’t have been as easy to read:<br />

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

To construct an empty array, pass no arguments to array( ):<br />

$addresses = array( );<br />

You can specify an initial key with => and then a list of values. The values are<br />

inserted into the array starting with that key, with subsequent values having sequential<br />

keys:<br />

$days = array(1 => 'Monday', 'Tuesday', 'Wednesday',<br />

'Thursday', 'Friday', 'Saturday', 'Sunday');<br />

// 2 is Tuesday, 3 is Wednesday, etc.<br />

If the initial index is a non-numeric string, subsequent indexes are integers beginning<br />

at 0. Thus, the following code is probably a mistake:<br />

$whoops = array('Friday' => 'Black', 'Brown', 'Green');<br />

// same as<br />

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

Adding Values to the End of an Array<br />

To insert more values into the end of an existing indexed array, use the [] syntax:<br />

$family = array('Fred', 'Wilma');<br />

$family[] = 'Pebbles'; // $family[2] is 'Pebbles'<br />

This construct assumes the array’s indexes are numbers and assigns elements into the<br />

next available numeric index, starting from 0. Attempting to append to an associative<br />

118 | Chapter 5: Arrays<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!