Tutorials

PHP Loops

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

Going Around In Circles

The Initialization
This is where the loop starts. We tell the "for" loop where to start by assigning the starting number to a variable $x. In this example, our starting number is represented by $start - what the user puts in from the form.

In a "for" loop, the initialization must always be a number. It doesn't have to be a whole number, or even positive, but it has to be a number, and it has to be initialized by assignment to a variable, so that PHP can keep track of counting each iteration of the loop. In other words, it has to have this basic format:

$x = $start;

The Condition
This is where we control how many times we want the loop to repeat, or iterate. A "for" loop counts from one number to some other number. This is where we tell PHP what that other number is. Without the condition, the loop will never stop repeating, and we would have what's called an infinite loop.

The condition must always check the initializing variable against a number value. It doesn't have to be a whole number, it can be positive or negative, but it has to be a number value. You can use any of the normal condition operators for the condition. Some basic formats (that are relevant to our example) for the condition are:
$x < $finish;
$x <= $finish;
$x != $finish;

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.