Membership
Main Menu
Forum Boards
Stats
- 20 tutorials
- 74,816 members
- 734,949 forum posts
- 13 blog posts
Tutorials
PHP Loops
Views: 25165
The Foreach Loop
A foreach loop is specially designed for working with array elements. A basic structure of a foreach loop looks like this:
foreach ($array as $value) {
instruction
}
In this loop, the $value is the initialization component. The condition and iteration comes from the $array. The $array represents an array. The loop starts an internal pointer at the beginning of the array, and assigns the value of that element to $value, and then executes the instructions. When the instructions are done, the pointer is moved to the next element of $array (the iteration). If there is no element (the end of the array), the condition evaluates false, and the loop ends.
Consider this example:
The foreach loop points to the first element of the $letters array, executes the instructions, moves to the next element, etc... and when it runs out of elements, the loop is over. The output would be:
a
b
c
The foreach loop accommodates associative arrays, as well. An associative array is an array that assigns a "name" to the element, or key, of the array. Example:
The output of this would be:
name : John
number : 123
age : 30
