How to Create a While Loop in PHP
Conditional statements and loops are powerful tools (in PHP or any other programming language) that help control the program flow. Like other programming languages, PHP has a set of conditional statements and loops that enables the script to perform a different action when a condition is or is not met. One of these loop statements is the while statement.
Things You'll Need
- PHP IDE or a text editor
- MySQL database server configured to work with PHP
- PHP 5, installed and properly configured
- Web server (preferably Apache)
Instructions
-
Create a While Loop in PHP
-
1
Define the variables you will use and assign them an initial value:
$count = 1;
$total = 15; -
2
Define the condition that is to be checked:
while ($count <= 10) -
-
3
Define the actions to be taken while the condition is still true:
{$total = $total + $count;
echo "The total amount is $total ";
$count++;
}
Check the Statement After You Create It
-
4
See if your code looks like this:
$count = 1;
$total = 15;
while ($count <= 10) {
$total = $total + $count;
echo "The total amount is $total";
$count++;
} -
5
Check for syntax errors and run the code. It must check if the count value is less than or equal to 10. While it is less than or equal to 10, the total value will be increased with the value of count. After each increase of the total value, the count variable is increased with 1 ($count++), so that the loop will end when the count value reaches 10.
-
1
Tips & Warnings
Write conditions that are true at the start. If the condition is false initially, the code block will not be executed at all. If this is what you want, then do it. In many cases, you don't know if the condition is true, but you still need to perform certain actions when the condition is true.
Write conditions that will be met at some point. If your condition will always be true, this will create an endless loop.
Pay attention to the syntax of the while loop. This is especially important if you have been programming languages other than PHP.