Specifications

Using Loops with each() and list()
Because the indices in this associative array are not numbers, we cannot use a simple counter
in a for loop to work with the array. The following code lists the contents of our $prices
array:
while( $element = each( $prices ) )
{
echo $element[ “key” ];
echo “ - “;
echo $element[ “value” ];
echo “<br>”;
}
The output of this script fragment is shown in Figure 3.2.
Using PHP
P
ART I
74
FIGURE 3.2
An each statement can be used to loop through arrays.
In Chapter 1, we looked at while loops and the echo statement. The preceding code uses the
each() function, which we have not used before. This function returns the current element in
an array and makes the next element the current one. Because we are calling each() within a
while loop, it returns every element in the array in turn and stops when the end of the array is
reached.
In this code, the variable $element is an array. When we call each(), it gives us an array with
four values and the four indexes to the array locations. The locations key and 0 contain the key
of the current element, and the locations
value and 1 contain the value of the current element.
Although it makes no difference which you choose, we have chosen to use the named loca-
tions, rather than the numbered ones.
There is a more elegant and more common way of doing the same thing. The function list()
can be used to split an array into a number of values. We can separate two of the values that
the each() function gives us like this:
$list( $product, $price ) = each( $prices );
05 7842 CH03 3/6/01 3:42 PM Page 74