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

An Introduction to Loops in PHP

By , About.com Guide

1 of 3

WHILE Loops

In PHP there are several different types of loops. Basically what a loop does is evaluate a statement as true or false. If it is true it executes some code and then alters the original statement and starts all over again by re-evaluating it. It continues to loop through the code like this until the statement becomes false.

Here is an example in its simplest form:

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

Basically what this does is: while a number is greater than or equal to 10 it prints the number. The ++ adds one to the number, however this could also be phrased as $num = $num + 1; Once the number becomes greater than 10, in our case it becomes 11, then it stops executing the code within the {brackets}

Below is an example of how you can combine a loop with a conditional

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

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 While - PHP Loops

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

All rights reserved.