Friday, October 23, 2009

Working with foreach Loops








Working with foreach Loops


There's a special loop, the foreach loop, that makes working with complex variables such as arrays easier. We'll get the details on foreach in the next chapter, but we'll take a quick look at it here. Arrays store multiple data items, and this loop lets you loop over arrays without using a loop index. Here's how you use it:



foreach (array_expression as $value) statement
foreach (array_expression as $key => $value) statement


You can see an example in phpforeach.php, Example 2-9, where foreach is looping over an array of fruits and echoing each to the browser window.


Example 2-9. Using the foreach loop, phpforeach.php



<HTML>
<HEAD><TITLE>Using the foreach loop</TITLE></HEAD>

<BODY>
<H1>Using the foreach loop</H1>
<?php
$arr = array("apples", "oranges", "bananas");
foreach ($arr as $value) {
echo "Current fruit: $value<BR>";
}
?>
</BODY>
</HTML>



The results appear in Figure 2-10; the loop was able to loop over all the items in the array automatically. The specifics of this loop are coming up in Chapter 3.


Figure 2-10. Using the foreach loop.

[View full size image]









    No comments: