www.pickatutorial.com Computer Tutorials

PHP foreach Loops. Free online PHP and MySQL Web Database Programming Tutorial...

Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script
Lessons PHP foreach Loop Bookmark and Share
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Lesson 24
Lesson 25
Lesson 26
Lesson 27
Lesson 28
Lesson 29
Lesson 30
Lesson 31
Lesson 32
Lesson 33
Lesson 34
Lesson 35
Lesson 36
Lesson 37
Lesson 38
Lesson 39
Lesson 40
Lesson 41
Lesson 42
Lesson 43
Lesson 44
The foreach statement is used in PHP to loop through arrays. The foreach statement works only on arrays, and will issue an error when we try to use it on a variable with a different data type or an uninitialized variable. It offers a convenient construct to iterate over arrays. There are two syntaxes available; the second is a minor but useful extension of the first:

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)
?>



Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.