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


Programming PHPProgramming PHPSearch this book

5.2. Identifying Elements of an Array

You can access specific values from an array using the array variable's name, followed by the element's key (sometimes called the index) within square brackets:

$age['Fred']
$shows[2]

The key can be either a string or an integer. String values that are equivalent to integer numbers (without leading zeros) are treated as integers. Thus, $array[3] and $array['3'] reference the same element, but $array['03'] references a different element. Negative numbers are valid keys, and they don't specify positions from the end of the array as they do in Perl.

You don't have to quote single-word strings. For instance, $age['Fred'] is the same as $age[Fred]. However, it's considered good PHP style to always use quotes, because quoteless keys are indistinguishable from constants. When you use a constant as an unquoted index, PHP uses the value of the constant as the index:

define('index',5);
echo $array[index];               // retrieves $array[5], not $array['index'];

You must use quotes if you're using interpolation to build the array index:

$age["Clone$number"]

However, don't quote the key if you're interpolating an array lookup:

// these are wrong
print "Hello, $person['name']";
print "Hello, $person["name"]";
// this is right
print "Hello, $person[name]";


Library Navigation Links

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