Login | Contact Us | Site Map | Resources

PHP Conditions & Loops

Home > PHP Tutorial > For


For loops can be used when you know in advance how many times a block of code should be run. They are more complex than while loops, but understandable once they are broken down and explained. They are more compact than while loops, making them popular for many uses.

Their syntax is: for (initialize; condition; increment) { action to take }

Instead of accepting only a single condition, like a while loop does, the for loop accepts three different expressions separated by semi-colons.

The first expression (initialize) sets, or initializes, a variable with a numerical value than can be used as a counter. When learning about "while" loops, we set this variable before the loop began, but "for" loops include this variable when beginning the loop. This expression is only run at the beginning of the loop, after which it is ignored.

The second expression is the condition, which behaves no different than the conditions that we have already discussed. It is checked at the beginning of every loop.

The third expression is the increment, which, in a while loop, is included as part of the action to be taken, but in a for loop is one of the expressions initially set. It is run each time the loop is run.

Let's see a for loop in action.

  $number = 75;
  for ($count=1; $count<=10; $count++) {
    echo $number . "<br>";
    $number += 75;

What our example is doing is using the $count variable as a counter to determine how many times the loop is run. It is set, evaluated, and incremented all in one statement. The block of code that follows simply echoes the current value of the $number variable, then adds 75 to that value. The loop is run 10 times, as specified in the condition.

The result will look like this:


For loops are fun to experiment with, and exhilarating when they actually do what you want them to for the first time ever!