In this tutorial, you learn how about While loop in PHP, its syntax, and how to use it to implement looping of a task, with example programs.

PHP While Loop

PHP While Loop executes a block of statements in a loop as long as the condition is true.

Syntax of While Loop

The syntax of PHP while loop is

</>
Copy
while (condition) {
  // while-block statement(s)
}

where

  • while is the keyword.
  • condition evaluates to a boolean value: true or false. condition is wrapped in parenthesis.
  • while-block statement(s) are a block of none, one or more statements. while-block statement(s) are enclosed in flower braces. If there is only one statement for while-block, then the flower braces are optional. But, that is a very rare case.

Examples

1. Print numbers from 0 to 3 using While loop

The following program is a simple example demonstrating the working of While loop for printing numbers from 0 to 3. Here the task is to print the numeric value in the variable, repeatedly in a loop.

PHP Program

</>
Copy
<?php
$i = 0;
while ( $i < 4 ) {
    echo "$i <br>";
    $i++;
}
?>

Output