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.

Identifying Elements of an Array<br />

You can access specific values from an array using the array variable’s name, followed<br />

by the element’s key (sometimes called the index) within square brackets:<br />

$age['Fred']<br />

$shows[2]<br />

The key can be either a string or an integer. String values that are equivalent to integer<br />

numbers (without leading zeros) are treated as integers. Thus, $array[3] and<br />

$array['3'] reference the same element, but $array['03'] references a different element.<br />

Negative numbers are valid keys, and they don’t specify positions from the<br />

end of the array as they do in Perl.<br />

You don’t have to quote single-word strings. For instance, $age['Fred'] is the same<br />

as $age[Fred]. However, it’s considered good <strong>PHP</strong> style to always use quotes,<br />

because quoteless keys are indistinguishable from constants. When you use a constant<br />

as an unquoted index, <strong>PHP</strong> uses the value of the constant as the index:<br />

define('index',5);<br />

echo $array[index]; // retrieves $array[5], not $array['index'];<br />

You must use quotes if you’re using interpolation to build the array index:<br />

$age["Clone$number"]<br />

However, don’t quote the key if you’re interpolating an array lookup:<br />

// these are wrong<br />

print "Hello, $person['name']";<br />

print "Hello, $person["name"]";<br />

// this is right<br />

print "Hello, $person[name]";<br />

Storing Data in Arrays<br />

Storing a value in an array will create the array if it didn’t already exist, but trying to<br />

retrieve a value from an array that hasn’t been defined yet won’t create the array. For<br />

example:<br />

// $addresses not defined before this point<br />

echo $addresses[0]; // prints nothing<br />

echo $addresses; // prints nothing<br />

$addresses[0] = 'spam@cyberpromo.net';<br />

echo $addresses; // prints "Array"<br />

Using simple assignment to initialize an array in your program leads to code like this:<br />

$addresses[0] = 'spam@cyberpromo.net';<br />

$addresses[1] = 'abuse@example.com';<br />

$addresses[2] = 'root@example.com';<br />

// ...<br />

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

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Storing Data in Arrays | 117

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

Saved successfully!

Ooh no, something went wrong!