25 Aug 09 PHP Programming Tutorial: While Loops



PHP While Loops will keep repeating as long as its conditions are true. The flow of the loop is:

1. You set a condition.
2. The condition is tested at the beginning of each loop.
3. If the condition is true, the code (statements) are executed. If false, the loop ends.

The basic structure of a While Loop is:

<?php
while (condition) { // begins the loop and sets condition
code // if loop is true, this code is executed
} // end of loop
?>

Let’s try a simple real life example. If we want to repeat a set of code five
times, we could do this:

<?php
$x = 1; // set the $x variable to a numeric value of 1
 
while ($x < 6) { // create a while loop to repeat as long as $x is less than 6
echo "This is number: $x"; // echo the current value of the variable
echo "<br />"; // add a new line for easy viewing
$x++; // add 1 to the value of the $x variable
}
?>

Output:
This is number 1
This is number 2
This is number 3
This is number 4
This is number 5

So what’s going on here?

1. First we created a simple variable and set it to 1. The $x variable is acting like a counter for us.

2. Then we created a While Loop and told PHP, “Hey, as long as $x is less than 6, could you please execute the code.”

3. Then after we do our echo statements, we tell PHP to add 1 to the variable.

4. After doing this five times, PHP sees that $x is NOT less than 6, so it stops executing the code.

Go back to Building PHP Scripts.

Tags: , , , ,

Leave a Comment