Skip to content

PHP Tutorial Loops

PHP while Loop

Lesson 92 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

A loop repeats code. The while loop keeps running its block as long as a condition is true.

index.php
PHP
<?php
$count = 1;

while ($count <= 3) {
    echo "Round $count\n";
    $count++;
}
Output
OUTPUT
Round 1
Round 2
Round 3

How it works

  1. PHP checks the condition ($count <= 3).
  2. If it is true, PHP runs the block, then goes back to step 1.
  3. If it is false, PHP leaves the loop.

The condition is checked before each round. If it is false from the start, the block never runs.

index.php
PHP
<?php
$count = 10;

while ($count <= 3) {
    echo "This never prints";
}

echo "Skipped the loop";
Output
OUTPUT
Skipped the loop

Change something inside the loop

Something inside the loop must eventually make the condition false. In the first example, $count++ does that. If you forget it, the loop never ends. That is an infinite loop, and it makes the script hang until PHP’s time limit stops it.

When while is the right tool

Use while when you do not know how many rounds you need. For example, “keep going until we run out”.

index.php
PHP
<?php
$money = 100;
$days = 0;

while ($money > 20) {
    $money -= 30;
    $days++;
}

echo "Money lasted $days days, $money left";
Output
OUTPUT
Money lasted 3 days, 10 left

Count down

index.php
PHP
<?php
$seconds = 3;

while ($seconds > 0) {
    echo $seconds . "...\n";
    $seconds--;
}

echo "Go!";
Output
OUTPUT
3...
2...
1...
Go!

Reading rows one at a time

You will meet while again in the database chapters, where it reads one record at a time until none are left. Here is the same idea with an array.

index.php
PHP
<?php
$queue = ["Ann", "Bob", "Cy"];

while ($name = array_shift($queue)) {
    echo "Serving $name\n";
}
Output
OUTPUT
Serving Ann
Serving Bob
Serving Cy

array_shift() removes and returns the first item. When the array is empty it returns null, which stops the loop.

warning
The forgotten update
If the variable in the condition never changes inside the loop, the loop never ends. Before you run a new while, ask: “what makes this stop?”