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

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.
ADVERTISEMENT

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

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

Output

PHP While Loop

In this program,

  • the condition is $i < 4.
  • while-block has two statements: the echo and increment statements.

Explanation

Let us see the step by step execution of the above program.

  1. Assign 0 to i.
  2. Evaluate the condition $i < 4. 0 < 4 is true. So, execute while-block.
    1. Execute echo statement.
    2. Increment i. Now i is 1.
  3. Evaluate the condition $i < 4. 1 < 4 is true. So, execute while-block.
    1. Execute echo statement.
    2. Increment i. Now i is 2.
  4. Evaluate the condition $i < 4. 2 < 4 is true. So, execute while-block.
    1. Execute echo statement.
    2. Increment i. Now i is 3.
  5. Evaluate the condition $i < 4. 3 < 4 is true. So, execute while-block.
    1. Execute echo statement.
    2. Increment i. Now i is 4.
  6. Evaluate the condition $i < 4. 4 < 4 is false. While loop execution is complete.

2. Print “Hello World” five times using While loop

In the following program, we repeat the task of printing the string value “Hello World” using While loop.

PHP Program

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

Conclusion

In this PHP Tutorial, we learned the syntax of PHP While Loop, and its working with the help of example program.