PHP While Loops

PHP while loops let you run a piece of code again and again. Learn how to use PHP while loops and do...while loops in this beginner tutorial.

PHP loops let you run a block of PHP code over and over again. They're great for repetitive tasks such as reading data records from a database, or displaying rows of a table in a Web page.

The PHP while loop is the simplest type of loop to understand. In this article you look at the syntax of a PHP while loop, and explore some example loops. You also look at do...while loops.

What is a while loop?

A while loop is a construct that lets you run a block of code repeatedly as long as a certain condition is true. As soon as the condition becomes false, the loop exits.

Here's the general syntax of a PHP while loop:


while ( condition ) {
  // This code is run as long as condition is true
}

// This code is run after the loop finishes

Here's how it works:

  1. The PHP engine tests the condition inside the parentheses.
  2. If the condition is true then the PHP engine runs the code inside the braces ({}), then retests the condition. If it's still true then the code inside the braces is run again, and so on.
  3. If the condition is false then the PHP engine exits the loop, and starts running any code after the closing brace.

Typically, you write the condition in such a way that it is true while you want your loop to run, and becomes false when you want your loop to exit. For example, if your loop should count to ten before exiting then the condition might be:


while ( $counter <= 10 ) {
...

You can use any expression as the condition in a while statement, as long as it evaluates to either true or false. You can use one or more PHP operators to build your condition expression.

A PHP while loop example

Here's a simple example script that uses a while loop to count from 1 to 10:


$counter = 1;

while ( $counter <= 10 ) {
  echo "I've counted to $counter<br />";
  $counter++;
}

echo "All done!";

When run, this code displays the following in a Web browser:


I've counted to 1
I've counted to 2
I've counted to 3
I've counted to 4
I've counted to 5
I've counted to 6
I've counted to 7
I've counted to 8
I've counted to 9
I've counted to 10
All done!

The script first sets a $counter variable to 1. Then it starts looping. Each time through the loop, $counter is tested to make sure it's still less than or equal to 10; as long as it is, the loop repeats. Inside the loop, the current value of $counter is displayed, then $counter is incremented by 1.

Once $counter reaches 11, the condition in the while loop becomes false and the loop exits, displaying the "All done!" message.

The PHP do...while loop

The do...while loop is a variation of the while loop. The only difference is that the expression is tested after the code block has been run, rather than before:


do {
  // This code is run at least once
} while ( condition )

// This code is run after the loop finishes

Here's how a do...while loop runs:

  1. The PHP engine first runs the code block inside the braces ({}).
  2. Next, the PHP engine tests the condition inside the parentheses.
  3. If the condition is true then the code inside the braces is run again, and so on.
  4. If the condition is false then the PHP engine exits the loop, and starts running any code after the closing brace.

You can see that, with a do...while loop, the code inside the loop is always run at least once, even if the condition is false to start with. This can be useful in certain situations. For example, if your condition includes a variable that is set inside the loop then you need to run the loop at least once before you can test the condition.

Here's an example of a do...while loop — a simple number-guessing game:


$theNumber = rand ( 1, 10 );

do {
  $myGuess = rand ( 1, 10 );
  echo "I'm guessing: $myGuess</br />";
} while ( $myGuess != $theNumber );

echo "I got it! It's $myGuess!<br />";

The script displays something like this:


I'm guessing: 3
I'm guessing: 5
I'm guessing: 7
I'm guessing: 2
I got it! It's 2!

First, the script sets a new variable, $theNumber, to a random number between 1 and 10. Then it begins the do...while loop. Within the loop, the script sets another variable, $myGuess, to another random number between 1 and 10, and displays the guess.

Next, the loop condition tests to see if $theNumber and $myGuess are different; if they are then the loop runs again so that another guess can be made. This repeats until $myGuess equals $theNumber; at this point the loop exits and the script displays a success message.

The built-in PHP function rand() takes two numbers and returns a whole random number between those two numbers (inclusive).

You've now seen how to use PHP's while and do...while loops to write code that runs repeatedly as long as a condition is met. Loops are simple yet powerful constructs that you'll use often in your PHP scripts. Happy coding!

Learn PHP With Ease!

Written by Matt Doyle — ELATED's resident Web programming expert — Beginning PHP 5.3 is a complete introduction to PHP, covering everything in these tutorials and lots more besides. Find out how to:

  • Set up PHP on your computer
  • Use strings, arrays, functions and objects
  • Create interactive Web forms
  • Handle cookies and sessions
  • Work with files on the server
  • Build database-driven sites with MySQL
  • Send emails from your scripts
  • Create images on the fly with PHP
  • Work with regular expressions
  • Write robust, secure PHP applications

...and lots more!

“What a pleasure it's been spending hours and hours studying PHP with this magical book.” — Lulio, Florida
“The book is not only great for learning, but I find myself using it constantly as a reference as well!” — David A. Stoltz

Buy Beginning PHP 5.3 now from Amazon.comBeginning PHP 5.3 or Amazon.co.ukBeginning PHP 5.3.

Follow Elated

Related articles

Responses to this article

There are no responses yet.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page