1. Home
  2. Computing & Technology
  3. PHP / MySQL

An Introduction to Loops in PHP

By Angela Bradley, About.com

2 of 3

FOR Loops

A FOR loop is very similar to a WHILE loop in that it continues to process a block of code until a statement becomes false, however everything is defined in a single line. The basic structure for a FOR loop is:

for ( start; conditional; increment) { code to execute; }

Let's go back to our first example using the WHILE loop, where we printed out the numbers 1 through 10 and do the same thing using a FOR loop.

<?php
for ($num=1; $num <= 10; $num++ )
{
print $num . " ";
}
?>

The FOR loop can also be used in conjunction with a conditional, just like we did with the WHILE loop:

<?php
for ($num=1; $num <= 10; $num++ )
{
if ($num < 5)
{
print $num . " is less than 5 <br>";
}
else
{
print $num . " is not less than 5 <br>";
}
}
?>

Index: An Introduction to Loops in PHP

  1. WHILE Loops
  2. FOR Loops
  3. FOREACH Loops

2 of 3

Explore PHP / MySQL

More from About.com

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. PHP Functions
  5. PHP Tutorial - PHP FOR - PHP Loops

©2008 About.com, a part of The New York Times Company.

All rights reserved.