![]() |
|
PHP foreach Loops. Free online PHP and MySQL Web Database Programming Tutorial... |
| Lessons | PHP foreach Loop |
|
|
1. foreach (array_expression as $value) statement 2. foreach (array_expression as $key => $value) statement The first form loops over the array given by array_expression. On each loop iteration, the value of the current element is assigned to $value variable and the internal array pointer is moved forward by one. The second form does the same thing, except that the current element's key is also assigned to the variable $key on each loop iteration. As of PHP 5, it is now possible to iterate objects too. Let's see its syntax: foreach (array as value) { code to be executed; } Example The following example demonstrates a loop that prints the values of the given array: <html> <body> <?php $arr=array("one", "two", "three", "four", "five"); foreach ($arr as $value) { echo "Value: " . $value . "<br />"; } ?> </body> </html> Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. Therefore any changes made to it inside the foreach are not reflected in the original array. If the array is required to reflect the changes made inside the foreach, the array variable $value has to be preceded with &. This will assign reference instead of copying the value. Consider the following example: <?php $arrayOfNumbers = array(1, 2, 3, 4, 5); foreach ($arrayOfNumbers as &$value) { $value = $value * 2; } // $arrayOfNumbers is now array(2, 4, 6, 8, 10) ?>
Next: PHP Switch Statement
|