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

An Introduction to Loops in PHP

By , About.com Guide

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>";
}
}
?>

Explore PHP / MySQL
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

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

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

All rights reserved.