Wednesday, June 3, 2009

PHP - For Loop

The common tasks that are covered by a for loop are:

  1. Set a counter variable to some initial value.
  2. Check to see if the conditional statement is true.
  3. Execute the code within the loop.
  4. Increment a counter at the end of each iteration through the loop.
The basic structure of the for loop:

for ( initialize a counter; conditional statement; increment a counter){
do this code;
}


For loop has three statements.

  • In the first statement, we initialize a counter variable to an number value.
  • In the second statement, we set a condition (a max/min number value) until the counter is reached.
  • In the third statement, we set a value by how much we want the counter variable to incremented by.
Example:

<?php

for($i=0; $i<=5; $i=$i+1)
{
echo $i." ";
}

?>

Will Print number through 0 to 5