PHP While Loop

••• PHP While Loop

Sometimes while writing programs we might need to repeat same code or task again and again. for this we use the PHP While Loop Statement in PHP Programming.

In this article we learn about the PHP While Loop For this PHP provides the feature of looping which allows the certain block of code to be executed repeatedly unless or until some sort of condition is satisfied even though the code appears once in the program.

PHP Programming Supports 4 Types of Looping:

  1. while loops
  2. do..while loops
  3. for loops
  4. foreach loops

PHP While Loop

The while statement will execute a block of code if and as long as a test expression is true.

If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.

The while loop executes a block of code as long as the specified condition is true.

Syntex of PHP While Loop statement

while (condition)
    // block of code to be executed

How PHP While loop work in PHP then?

As shown in the above structure a condition is placed which determines how many times the code is to be repeated.

Before entering inside the while loop the condition is checked, and if it is true the code block inside the while loop is executed and again after the operation condition is checked and the repetition of code is continued until the condition becomes false.



This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 5 when the evaluation is false and the loop ends.

$x = 1;

while ( $x <= 5) {

    echo "The Number is: $x <br>";


This will produce the following result

The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

Here is the break down of how a while loop functions when your script is executing:

  1. The conditional statement is checked. If it is true, then (2) occurs. If it is false, then (4) occurs.
  2. The code within the while loop is executed.
  3. The process starts again at (1). Effectively “looping” back.
  4. If the conditional statement is false, then the code within is not executed and there is no more looping. The code following the while loop is then executed like normal.