The foreach Statement


The foreach Statement

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

The PHP foreach statement gives you an easy way to iterate over arrays. This statement works only on arrays (you'll get an error when you try to use it on anything else).

The first form of this loop as shown here loops over the array given by array_expression. In each iteration, the value of the current element in the array is automatically assigned to $value, and the loop moves on to the next element.

The second form of this loop does the same thing, except that the current element's key will also be assigned to the variable $key in each iteration.

Here's an example:

 <?php     $array = array("grapes", "grapefruit", "bananas");     foreach ($array as $value) {         echo "The current value is $value\n";     } ?> 

If you prefer, you can also display the key during each iteration:

 <?php     $array = array("grapes", "grapefruit", "bananas");     foreach ($array as $key => $value) {         echo "The current key is $key and the current value is $value\n";     } ?> 



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net