Specifications

price => 10
),
array( Code => “SPK”,
Description => “Spark Plugs”,
price =>4
)
);
This array is easier to work with if you want to retrieve a single value. It is easier to remember
that the description is stored in the Description column than to remember that it is stored in
column 1. Using associative arrays, you do not need to remember that an item is stored at
[x][y]. You can easily find your data by referring to a location with meaningful row and col-
umn names.
We do however lose the ability to use a simple for loop to step through each column in turn.
Here is one way to write code to display this array:
for ( $row = 0; $row < 3; $row++ )
{
echo “|”.$products[$row][“Code”].”|”.$products[$row][“Description”].
“|”.$products[$row][“Price”].”|<BR>”;
}
Using a for loop, we can step through the outer, numerically indexed $products array. Each
row in our $products array is an associative array. Using the each() and list() functions in a
while loop, we can step through the associative arrays. Therefore, we need a while loop inside
a for loop.
for ( $row = 0; $row < 3; $row++ )
{
while ( list( $key, $value ) = each( $products[ $row ] ) )
{
echo “|$value”;
}
echo “|<BR>”;
}
We do not need to stop at two dimensionsin the same way that array elements can hold new
arrays, those new arrays in turn can hold more arrays.
A three-dimensional array has height, width, and depth. If you are comfortable thinking of a
two-dimensional array as a table with rows and columns, imagine a pile or deck of those
tables. Each element will be referenced by its layer, row, and column.
If Bob divided his products into categories, we could use a three-dimensional array to store
them. Figure 3.4 shows Bobs products in a three-dimensional array.
Using Arrays
C
HAPTER 3
3
USING ARRAYS
77
05 7842 CH03 3/6/01 3:42 PM Page 77