PHP while

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: PHP (php)

How it works.

  • First, PHP evaluates the expression. If the result is true, PHP executes the statement.
  • Then, PHP re-evaluates the expression again. If it’s still true, PHP executes the statement again. However, if the expression is false, 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: PHP (php)

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: