Summary: in this tutorial, you will learn how to use the PHP while
statement to execute a code block repeatedly as long as a condition is true
.
Introduction to the PHP while statement
The while
statement executes a code block as long as an expression
is true
. The syntax of the while
statement is as follows:
<?php
while (expression) {
statement;
}
Code language: HTML, XML (xml)
How it works.
- First, PHP evaluates the
expression
. If the result istrue
, PHP executes thestatement
. - Then, PHP re-evaluates the
expression
again. If it’s stilltrue
, PHP executes the statement again. However, if theexpression
isfalse
, the loop ends.
If the expression
evaluates to false
before the first iteration starts, the loop ends immediately.
Since PHP evaluates the expression
before each iteration, the while
loop is also known as a pretest loop.
The while
doesn’t require curly braces if you have one statement in the loop body:
<?php
while (expression)
statement;
Code language: HTML, XML (xml)
However, it’s a good practice to always include curly braces with the while
statement even though you have one statement to execute.
The following flowchart illustrates how the while
statement works:
PHP while loop example
The following example uses a while
loop to add whole numbers from 1 to 10:
<?php
$total = 0;
$number = 1;
while ($number <= 10) {
$total += $number;
$number++;
}
echo $total;
Code language: HTML, XML (xml)
Output:
55
The alternative syntax for the PHP while loop
The alternative syntax for the while statement is as follows:
<?php
while (expression):
statement;
endwhile;
Code language: HTML, XML (xml)
The following uses the alternative syntax of the while
statement to sum the whole numbers from 1 to 10.
<?php
$total = 0;
$number = 1;
while ($number <= 10) :
$total += $number;
$number++;
endwhile;
echo $total;
Code language: HTML, XML (xml)
Output:
55
Summary
- Use the PHP while loop statement to execute a code block as long as a condition is true.