Page 147 - Beginning PHP 5.3
P. 147
Chapter 6: Arrays
This works, but be careful. Just because an indexed array has, say, four elements, it doesn ’ t necessarily
mean that the last element has an index of 3! Consider the following (somewhat contrived) example:
// Create a sparse indexed array
$authors = array( 0 = > “Steinbeck”, 1 = > “Kafka”, 2= > “Tolkien”, 47 = >
“Dickens” );
$lastIndex = count( $authors ) - 1;
echo $authors[$lastIndex]; // Generates an “Undefined offset” notice
Although this array has numeric keys, which in one sense makes it an indexed array, the keys are not
consecutive. You could also think of the array as an associative array with numeric keys! As mentioned
at the start of the chapter, PHP doesn ’ t distinguish internally between indexed and associative arrays,
hence it ’ s possible to create indexed arrays with non - consecutive numeric indices. Although the
$authors array ’ s highest index is 47 , the array contains four elements, not 48. (These types of arrays are
often called sparse arrays .)
So when the script tries to access the last element ( “ Dickens “ ) using $lastIndex — which is set to 3 , or
one less than the return value of count() — PHP generates an “ Undefined offset ” notice, and the
echo() statement prints an empty string.
Having said all this, provided you know that an indexed array contains consecutively numbered
indices, you can assume that, for example, the 30th element in the array will always have an index of 29 .
If you ’ re in doubt you can use the functions described in the next section — “ Stepping Through an
Array ” — to retrieve the element you ’ re after.
Stepping Through an Array
You ’ ve already learned that you can access any element in an array using its key — whether numeric (in
the case of indexed arrays) or string (in the case of associative arrays). But what if you don ’ t know all of the
keys in an array in advance?
As you saw in the previous section, it ’ s possible to create indexed arrays where the indices aren ’ t
consecutively numbered from zero, but are instead arbitrary numbers. Furthermore, an associative
array ’ s keys don ’ t have to follow any pattern either — one element ’ s key might be “ elephant ” while
the next element ’ s key could be “ teacup “ — so unless you know the keys of the array in advance you ’ re
going to find it hard to access its elements!
Fortunately, PHP provides you with a suite of array - access functions that you can use to step through
each element in an array, regardless of how the elements are indexed. When you create an array, PHP
remembers the order that the elements were created in, and maintains an internal pointer to the elements
in the array. This pointer initially points to the first element that was created, but you can move the
pointer forward and backward through the array at will.
109
9/21/09 9:00:11 AM
c06.indd 109
c06.indd 109 9/21/09 9:00:11 AM