How to Create a Do While Statement in PHP
Like any other programming language, PHP uses conditional statements to trigger a different action when a condition is or is not met. One of these statements is the do while statement. Conditional statements like the do while statement are very powerful because, without them, it would not be possible to control the program flow.
Things You'll Need
- PHP 5, installed and properly configured
- MySQL database server, configured for work with PHP
- Web server
- PHP IDE
Instructions
-
Create a Do While Statement in PHP
-
1
Define the variables you will use. Next, assign them an initial value:
$count = 1;
$total = 15; -
2
Define the actions to be taken, no matter if the condition is true or false:
do
{
$total = $total + $count;
echo "The total amount is $total ";
$count++;
} -
-
3
Define the condition that is to be checked:
while ($count <= 10)
Double-Check the Statement
-
4
See if your code looks like this:
$count = 1;
$total = 15;
do {
$total = $total + $count;
echo "The total amount is $total ";
$count++;
}while ($count <= 10) -
5
Check for syntax errors and then run the code. The total value will be increased with the value of count. Then, the program checks to see if the count value is less than or equal to 10. While it is less than or equal to 10, the loop executes again, but each loop increases the count variable with 1 ($count++).
-
1
Tips & Warnings
The do while statement is very similar to the while statement. The only difference is that the block of code will be executed at least once, even if the condition is initially false.
Pay attention to the syntax of the do while statement you create, particularly if you are new to PHP.
Write conditions that will be met at some point. A condition that will always be true will create an endless loop.