While Loop

JA JASWANT Updated 17 Oct 2026
6 min read ·Lesson 6 of 248
In this post

What Is a while Loop? In simple terms: A while loop keeps repeating a block of code as long as a condition is true. It checks the condition before every repetition. Technically: while evaluates its co

What Is a while Loop?

In simple terms: A while loop keeps repeating a block of code as long as a condition is true. It checks the condition before every repetition.

Technically: while evaluates its condition; if the result (converted to boolean) is true, it executes the body and then evaluates the condition again. When the condition becomes false, execution continues after the loop. Because the condition is checked first, the body may run zero times.

Why It Is Needed

while is the right loop when you do not know in advance how many repetitions are needed:

  • Read lines from a file until there are no more.
  • Process jobs from a queue until it is empty.
  • Retry an operation until it succeeds or a limit is reached.
  • Repeat a calculation until a target value is reached.

Syntax

while (condition) {
    // code to repeat
}

Flow

        ┌─────────────┐
   ┌───►│ condition ? │── false ──► continue after the loop
   │    └──────┬──────┘
   │        true
   │           ▼
   │      [ loop body ]
   └───────────┘

Example: Countdown

<?php
$seconds = 5;

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

echo "Started!\n";

Output

Starting in 5...
Starting in 4...
Starting in 3...
Starting in 2...
Starting in 1...
Started!

How It Works

  1. $seconds starts at 5.
  2. Before each iteration, PHP checks $seconds > 0.
  3. The body prints a message and decreases $seconds by 1.
  4. After the fifth iteration, $seconds is 0, the condition is false, and the loop ends.

The line $seconds--; is essential: it moves the loop toward its end condition. Without it, the condition would stay true forever.


The Body May Not Run at All

<?php
$stock = 0;

while ($stock > 0) {
    echo "Selling one item\n";
    $stock--;
}

echo "Done (stock: $stock)\n";

Output

Done (stock: 0)

The condition is false from the start, so the body never runs. This is the key difference from do...while, which always runs its body at least once (see Do While Loop).


Repeating Until a Target Is Reached

while naturally expresses "keep going until …":

<?php
$balance = 10000;
$annualRate = 0.08;
$years = 0;

while ($balance < 20000) {
    $balance *= 1 + $annualRate;
    $years++;
}

echo "It takes $years years to double the investment.\n";
echo "Final balance: ₹" . number_format($balance, 2) . "\n";

Output

It takes 10 years to double the investment.
Final balance: ₹21,589.25

How It Works

  • Each iteration applies one year of 8% growth and counts the year.
  • The loop stops as soon as the balance reaches ₹20,000 or more.
  • You did not need to know the number of years in advance — the condition decides.

Processing Digits of a Number

<?php
$number = 4729;
$sum = 0;

while ($number > 0) {
    $sum += $number % 10;          // last digit
    $number = intdiv($number, 10); // remove last digit
}

echo "Digit sum: $sum\n";

Output

Digit sum: 22

% 10 extracts the last digit, and intdiv($number, 10) removes it. The loop runs once per digit — however many digits the number has.


Reading Data Until It Runs Out

A very common while pattern assigns a value in the condition and stops when the source returns false or null.

Reading Lines From a Stream

<?php
$stream = fopen('php://memory', 'r+');
fwrite($stream, "apple\nbanana\ncherry\n");
rewind($stream);

$lineNumber = 0;

while (($line = fgets($stream)) !== false) {
    $lineNumber++;
    echo "$lineNumber: " . trim($line) . "\n";
}

fclose($stream);

Output

1: apple
2: banana
3: cherry

How It Works

  1. php://memory is a temporary in-memory stream, used here so the example needs no file on disk. fwrite() adds text and rewind() moves back to the start.
  2. fgets() returns the next line, or false when there are no more lines.
  3. ($line = fgets($stream)) !== false assigns the line and checks it in one step. The parentheses are required, and the strict comparison matters: a line containing only "0" is falsy but valid.
  4. trim() removes the newline at the end of each line.

The same pattern reads real files (fopen('data.txt', 'r')), CSV rows (fgetcsv()), and database results.

Processing a Queue

<?php
$queue = ['resize photo-1.jpg', 'resize photo-2.jpg', 'send welcome email'];

while ($queue !== []) {
    $task = array_shift($queue);
    echo "Processing: $task (" . count($queue) . " left)\n";
}

Output

Processing: resize photo-1.jpg (2 left)
Processing: resize photo-2.jpg (1 left)
Processing: send welcome email (0 left)

array_shift() removes the first element, so the array shrinks with each iteration until it is empty.


Retrying With a Limit

When an operation may fail temporarily (a network call, for example), while can retry it — but always with a maximum number of attempts.

<?php
// Simulated results of three attempts: fail, fail, succeed
$simulatedResults = [false, false, true];

$maxAttempts = 5;
$attempt = 0;
$success = false;

while (!$success && $attempt < $maxAttempts) {
    $attempt++;
    $success = $simulatedResults[$attempt - 1] ?? true;

    echo "Attempt $attempt: " . ($success ? "success" : "failed") . "\n";
}

echo $success ? "Completed after $attempt attempt(s)\n" : "Gave up after $maxAttempts attempts\n";

Output

Attempt 1: failed
Attempt 2: failed
Attempt 3: success
Completed after 3 attempt(s)

Why Both Conditions Matter

  • !$success stops the loop as soon as an attempt succeeds.
  • $attempt < $maxAttempts guarantees the loop ends even if the operation never succeeds — preventing an infinite loop.

In real code, the simulated array would be replaced by the actual operation, and a short delay (for example usleep()) is often added between attempts.


while (true) With break

Sometimes the exit condition is easiest to check in the middle of the loop. An intentional infinite loop with break expresses this:

<?php
$commands = ['status', 'help', 'quit', 'status'];

while (true) {
    $command = array_shift($commands);

    if ($command === null || $command === 'quit') {
        echo "Exiting\n";
        break;
    }

    echo "Running command: $command\n";
}

Output

Running command: status
Running command: help
Exiting

The loop processes commands until it reads quit (or runs out), so the last status is never executed. Every while (true) loop must have a reachable break or return.


Alternative Syntax

In templates, while can use endwhile;:

<?php $remaining = 3; ?>
<?php while ($remaining > 0): ?>
<span>Seat <?= $remaining ?> available</span>
<?php $remaining--; ?>
<?php endwhile; ?>

Output (HTML)

<span>Seat 3 available</span>
<span>Seat 2 available</span>
<span>Seat 1 available</span>

foreach is more common in templates, but this form works the same way.


Common Mistakes

Forgetting to Change the Condition

$i = 1;
while ($i <= 3) {
    echo $i;
}

Effect: Infinite loop — $i never changes.

Fix: Update the variable inside the loop ($i++).

Updating in the Wrong Direction

$i = 10;
while ($i > 0) {
    $i++;   // should be $i--
}

Effect: The condition stays true forever (until the integer overflows to a float, which is still greater than 0).

Fix: Make sure each iteration moves toward making the condition false.

Loose Checks When Reading Data

Effect: while ($line = fgets($stream)) stops early at a line containing "0", because "0" is falsy.

Fix: Compare strictly: while (($line = fgets($stream)) !== false).

Retrying Without a Limit

Effect: A permanently failing operation causes an endless loop.

Fix: Always add a maximum attempt count.

Using while Where foreach Fits

Effect: Manual index handling and off-by-one errors when iterating arrays.

Fix: Use foreach for arrays; use while for "until" conditions.


Best Practices

  • Use while when the number of iterations depends on data or results, not on a fixed count.
  • Make sure every iteration moves toward the end condition.
  • Use strict comparisons (!== false, !== null) when assigning in the condition.
  • Add attempt limits to retry loops, and a reachable break to while (true) loops.
  • Prefer for for counting and foreach for arrays.

Official reference: https://www.php.net/manual/en/control-structures.while.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE PHP Type Juggling MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PSR-4 Autoloading Installing Extensions (PECL / PIE) OPcache & Performance PHP-FPM Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Shopping Cart with Sessions Project: REST API with PHP DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files
Ask about this post
AI Ask about this post

Ask questions about While Loop and get answers drawn from it.

Signed-in readers only.