Page 156 - Beginning PHP 5.3
P. 156
Part II: Learning the Language
Figure 6-4
As you can see, this script creates an indexed array, $myBooks , that contains four elements with the keys
0 , 1 , 2 , and 3 . Each element is, in turn, an associative array that contains three elements with keys of
“ title ”, “ author , and “ pubYear .
”
”
Although this array is a simple example, it gives you some idea of the power of multidimensional arrays.
You could potentially store thousands and thousands of books in this array, with as much information as
you like about each book.
Accessing Elements of Multidimensional Arrays
Using the square bracket syntax that you ’ ve already learned, you can access any element within a
multidimensional array. Here are some examples (these work on the $myBooks array just shown):
// Displays “Array ( [title] = > The Trial [author] = > Franz Kafka [pubYear]
= > 1925 )”;
print_r( $myBooks[1] );
// Displays “The Trial”
echo “ < br/ > ” . $myBooks[1][“title”] . “ < br/ > ”;
// Displays “1859”
echo $myBooks[3][“pubYear”] . “ < br/ > ”;
118
9/21/09 9:00:15 AM
c06.indd 118
c06.indd 118 9/21/09 9:00:15 AM