PHP Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 3.00

"for" Statements

This section describes how 'for' statements works in PHP. One or more statements are repeatedly executed as long as the specified condition is true. 'for' statements has extra expressions for loop initialization and loop control update.

The "for" statement is the most complex loop statement in PHP. There are 4 forms of "while" statements supported in PHP:

1. Empty-statement "for":

   for (initial_exepression; stop_condition; repeating_expression);

2. Single-statement "for":

   for (initial_exepression; stop_condition; repeating_expression)
      statement;

3. Multi-statement "for":

   for (initial_exepression; stop_condition; repeating_expression) {
      statement;
      statement;
      ...
   }

4. Multi-statement "for ... endfor":

   for (initial_exepression; stop_condition; repeating_expression):
      statement;
      statement;
      ...
   endfor;

All forms of "for" statements are executed like this:

Step 1: "initial_exepression" is evaluated unconditionally. The "initial_exepression" is usually used to assign the initial value to a loop control variable, like $i=0.

Step 2: Evaluate "stop_condition" as a Boolean value. The "stop_condition" is usually a comparison expression against the loop control variable, like $i<100.

Step 3: If "stop_condition" returns TRUE, continue with Step 5.

Step 4: If "stop_condition" returns "FALSE", terminate the loop.

Step 5: Execute the statement or statements enclosed in the loop.

Step 6: Evaluate "repeating_expression". The "repeating_expression" is usually an expression to increment the value of the loop control variable, like $i++.

Step 7: Continue with Step 2.

If you want to terminate the loop early, you can use the "break" statement inside the loop, which will terminate the loop immediately.

Last update: 2005.

Sections in This Chapter

"while" Statements

"while" Statement Examples

"for" Statements

"for" Statement Examples

"do ... while" Statements

"break" and "continue" Statements

Dr. Herong Yang, updated in 2009
"for" Statements