Identifying Elements of an Array

Before we look at creating an array, let’s look at the structure of an existing array. You can access specific values from an existing array using the array variable’s name, followed by the element’s key, or 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, but 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 and emits a warning:

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}"]

Although sometimes optional, you should also quote the key if you’re interpolating an array lookup to ensure that you get the value you expect:

// these are wrong
print "Hello, {$person['name']}";
print "Hello, {$person["name"]}";

Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.