The PHP For Statement

The PHP For Statement
The for statement is used to control a loop within your PHP program. It works like the while and do..while statements that we discussed in previous tutorials. The for statement tests an expression. If that expression is true the program will execute the task within the loop. Here is the basic code.

for (initialize variable exp; test expression; modify variable exp)
{ do this }
for ($number = 1; $number < 11; $number++)
{ echo "$number <br>"; }

The above example behaves the same as the while and do..while statements in the previous tutorials. However, if you compare these statements you will notice a few differences.

for()
The for statement begins with a for in front of two parenthesis. Inside the parenthesis are the three expressions that form the first part of the for statememt.

$number = 1;
initialize variable expression;
This expression sets the beginning value for the $number variable. This is the variable that will be used as a counter. In the while and do..while statements the counter variable is initialized outside of and before the loop statement. In the for statement the counter variable is initialized within the statement.

$number < 11;
test expression;
This is the control part of the loop statement. The loop will repeat as long as the test expression remains true. In the example the loop will continue until the $number variable is no longer less than 11.

$number++
modify variable expression
This expression increases the counter variable by 1. As with the while and do..while statements, this is a necessary part of the for statement. Without it the loop cannot change the value of the $number counter variable causing the loop to repeat indefinitely.

{ echo "$number <br>"; }
{ do this }
This is the part of the code that will be executed each time through the for statement as long as the test expression remains true. In the example the program will print the current value of the $number variable and the HTML <br> code to the web browser. Notice the differece from the while and do..while statements. In those statements the code that increased (changed) the value of the counter variable was included in this { do this } part of the code. But in the for statement it is within the parenthesis.

Here is what will appear in the web browser.

1
2
3
4
5
6
7
8
9
10






This site needs an editor - click to learn more!



RSS
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.