Specifications

This line uses each() to take the current element from $prices, return it as an array, and make
the next element current. It also uses list() to turn the 0 and 1 elements from the array
returned by each() into two new variables called $product and $price.
We can loop through the entire $prices array, echoing the contents using this short script.
while ( list( $product, $price ) = each( $prices ) )
echo “$product - $price<br>”;
This has the same output as the previous script, but is easier to read because list() allows us
to assign names to the variables.
One thing to note when using
each() is that the array keeps track of the current element. If we
want to use the array twice in the same script, we need to set the current element back to the
start of the array using the function
reset(). To loop through the prices array again, we type
the following:
reset($prices);
while ( list( $product, $price ) = each( $prices ) )
echo “$product - $price<br>”;
This sets the current element back to the start of the array, and allows us to go through again.
Multidimensional Arrays
Arrays do not have to be a simple list of keys and valueseach location in the array can hold
another array. This way, we can create a two-dimensional array. You can think of a two dimen-
sional array as a matrix, or grid, with width and height or rows and columns.
If we want to store more than one piece of data about each of Bobs products, we could use a
two-dimensional array.
Figure 3.3 shows Bobs products represented as a two-dimensional array with each row repre-
senting an individual product and each column representing a stored product attribute.
Using Arrays
C
HAPTER 3
3
USING ARRAYS
75
Code Description
product attribute
product
Price
TIR Tires 100
OIL Oil 10
SPK Spark Plugs 4
F
IGURE 3.3
We can store more information about Bobs products in a two-dimensional array.
05 7842 CH03 3/6/01 3:42 PM Page 75