Make your own free website on Tripod.com

Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

The forLooping Construct

a for loop supported in PHP is identical to that available in many other programming languages. Immediately perl, java and C++ come to mind. It makes use of the following syntax:

for(initialization expression; test expression; loop expression){
	PHP Statement 1;
	PHP Statement 2;
	...
}

The innards of the for construct are made up of three expressions:

The first expression is the initialization list - This is executed only once at the beginning of the loop. In this section you put any variables that need to be set BEFORE the loop starts eg setting/resetting counters.

If there is no initialization required, you may leave this part blank in which case the top part of your for loop will look like this:

for(; test expression; loop expression)

The second part of the for loop is the test expression. This part is evaluated EVERY iteration. If this expression evaluates to true, PHP repeats the loop structure and exits the loop when the test expression evaluates to false. Again just as in the previous case, this part may be omitted.

You might be asking. "If this part is the one that determines the ending of the loop, how comes it can be omitted. How will PHP know when to stop? Woun't this create an endless loop?"

TRUE. If no measures are put in place WITHIN the loop itself and the test expression is omitted, then we get an endless loop. When the test expression is left out, the code itself should have a conditional break; somewhere.

The last part of the for loop is the loop expression. Again this too can be omitted. The loop expression is evaluated EVERY iteration. This section is ideal for counter increments.

Let's take an example. The following code fragment prints all the multiples of 5 between 0 and 100:

for($counter = 0; $counter <= 100; $counter += 5){
	print $counter;
}

Since the last part (loop esxpression) is repeated in EVERY iteration, we can put the third line in it and separate it from the increment by a comma:

for($counter = 0; $counter <= 100; $counter += 5, print $counter);

To omit all the innards of the for will mean that all the evaluation will have to be done within the loop itself. That notwithstanding, all the semi-colons must be included:

$counter = 0;
for(;;){
	$counter += 5;
	if($counter > 100){
		break;
	}
	print $counter;
}

<< The do.. while Iteration Construct | The foreach Iteration Construct else >>

JamHitz Productions