Page 151 - Beginning PHP 5.3
P. 151
Chapter 6: Arrays
< body >
< h1 > Using each() with a while loop < /h1 >
< dl >
< ?php
$myBook = array( “title” = > “The Grapes of Wrath”,
“author” = > “John Steinbeck”,
“pubYear” = > 1939 );
while ( $element = each( $myBook ) ) {
echo “ < dt > $element[0] < /dt > ”;
echo “ < dd > $element[1] < /dd > ”;
}
? >
< /dl >
< /body >
< /html >
Figure 6-3
The while loop continues as long as each() keeps returning a four - element array (which evaluates to
true ). When the end of the array is reached, each() returns false and the loop finishes.
Looping Through Arrays with foreach
As you just saw, it ’ s easy to use each() in combination with while to loop through all the elements of
an array. In fact, there ’ s an even easier way: you can use PHP ’ s foreach statement.
113
9/21/09 9:00:13 AM
c06.indd 113
c06.indd 113 9/21/09 9:00:13 AM