1. Computing

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

Related Video
Basic PHP Syntax
Using PHP With HTML
  1. About.com
  2. Computing
  3. PHP / MySQL
  4. PHP Functions
  5. PHP Tutorial - PHP While - PHP Loops

©2013 About.com. All rights reserved.