PHP Tutorial – For Loops

The “for loop” execute a block of code a specified number of times while a specified condition is true.

Syntax


for (init; condition; increment)
{
    code to be executed;
}


The “for” loop holds three parameters. The init can be any piece of code that needs to be executed once at the beginning of the loop. In most cases init is used to set a counter. The condition is used to evaluate if the loop needs to continue. The evaluation is done for each loop iteration. If the evaluation is FALSE, the loop will end.

A “for loop” Example

Let’s look at an example:


<html>
<body>

<?php
    for ($x=0; $x<=5; $x++)
    {
         echo "Number is " . $x . "<br />";
    }
?>

</body>
</html>

First X is set to zero. Then the condition is checked; is X less or equal 5. If true the code between the curly brackets. X will increase by 1 each time the loop runs.

Tip: a lot of people use i as the variable counter name. We don’t use i because there are fonts where the i and 1 look similar.

So the output of our example will be:


Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5

Also take a look at the other PHP language loop statements:

  • while – loop through a block of code while a specified condition is true
  • do…while – loop through a block of code once, and then repeats the loop as long as a specified condition is true
  • foreach – loops through a block of code for each element in an array
This entry was posted in PHP Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Tweet This! Tweet This! or use to share this post with others.

There are currently 3 responses to “PHP Tutorial – For Loops”

Why not let us know what you think by adding your own comment!

  1. Torrent Movie on April 21st, 2011:

    Heyy Thank you very much!!

  2. rene descarte on August 7th, 2012:

    May i ask am a bit confuse?If we set initialy the value of $x is zero
    and it satisfy that it is less than 5, would it be right if the output will start at “Number is 1″ instead of “Number is 0″?since we need to increment the $x by 1 each loop?

  3. William on July 6th, 2013:

    Rene,
    If the value of $x was initially set at 1, then the counter would start at 1. Understand that the value of the initializing variable can be anything that you set it at, but what you set it at will greatly effect the results you get. Hope that helps you out.

Leave a Reply: