PHP syntax: for loop basics

Home -> Programming -> Web -> PHP

13837 views

From the computer of: qmchenry (338 recipes)
Created: Feb 01, 2004     Updated: Jun 19, 2006


Add a comment

Add to:
Add to stumbleuponAdd to del.icio.usDigg itAdd to FURL

The for loop allows iteration a fixed number of times.





The basic for loop syntax is:

for (initialization; condition; incrementor) {
     code;
}


The initialization defines the loop variable and its initial value (such as $i=1). The loop will continue to iterate while the conditional expression evaluates as true (like $i<10). Each time the loop is executed, the incrementor code is exectued (the code $i++ would increment the loop variable $i by one; $i=$i*2 would double the loop variable $i each iteration).

Putting these together in a simple example,

for ($i=1; $i<=10; $i+=2) {
    echo "$i ";
}


This code would generate the output "1 3 5 7 9" since the variable $i starts at 1 and increments by two each loop until it is no longer less than or equal to 10.

Subscribe to the Tech-Recipes Newsletter

You can get tips like this delivered in your email every week!

Enter your Email

We will never, ever sell your email address or spam you.





Related recipes:

  PHP syntax: iterate over an associative array
  PHP: Rename or move a file on the server
  PHP conditional syntax: inequality
  PHP syntax: comments
  PHP conditional syntax: less than
  PHP syntax: create an associative array
  PHP syntax: iterate over an array
  PHP comparison syntax: equality
  PHP conditional syntax: greater than
  Redirect to another web page using PHP

 

Sponsored links

 

Login

Nickname

Password

Don't have an account yet? You can create one. As a registered user you have some advantages like theme manager, comments configuration and post comments with your name.