Prev | Current Page 178 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

62140);
}
// Example Two
for ($kilometers = 1; ; $kilometers++) {
if ($kilometers > 5) break;
printf("%d kilometers = %f miles
", $kilometers, $kilometers*0.62140);
}
CHAPTER 3 ?–  PHP BASICS 105
// Example Three
$kilometers = 1;
for (;;) {
// if $kilometers > 5 break out of the for loop.
if ($kilometers > 5) break;
printf("%d kilometers = %f miles
", $kilometers, $kilometers*0.62140);
$kilometers++;
}
The results for all three examples follow:
1 kilometers = 0.6214 miles
2 kilometers = 1.2428 miles
3 kilometers = 1.8642 miles
4 kilometers = 2.4856 miles
5 kilometers = 3.107 miles
The foreach Statement
The foreach looping construct syntax is adept at looping through arrays, pulling each
key/value pair from the array until all items have been retrieved or some other internal
conditional has been met. Two syntax variations are available, each of which is presented
with an example.
The first syntax variant strips each value from the array, moving the pointer closer
to the end with each iteration. The following is its syntax:
foreach (array_expr as $value) {
statement
}
Consider this example. Suppose you want to output an array of links:
$links = array("www.apress.com","www.php.net","www.apache.org");
echo "Online Resources:
";
foreach($links as $link) {
echo "$link
";
}
?>
106 CHAPTER 3 ?–  PHP B ASICS
This would result in the following:
Online Resources:

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190