Tutorials

PHP Loops

by Crayon Violent on Jun 19, 2008 2:46:30 PM

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

Comments

Again, very nice CV. Only thing i would mention is that it's not strictly true that a for loop requires all 3 parameters. This is a perfectly valid for loop:

As is this:

Of course, they serve no real useful purprose (use a while loop, it's easier to follow) but i had to find something wrong with it :P

1. Ben Smithers on Jun 20, 2008 5:07:40 AM

Ah you are right, but in order for the loops to function properly, they still need to have all the components somewhere. Your first example, while syntactically correct, would in and of itself be an infinite loop. Using your first example, you would have to put the condition and iteration inside the instruction. Example:

I'm glad you pointed that out though : )

2. Crayon Violent on Jun 20, 2008 10:19:46 AM

A concise explanation of loops. Very good.

3. kahratka on Jun 20, 2008 10:32:40 AM
Login or register to post a comment.