In web development, repetitive tasks—such as displaying lists of 50 student records, calculating monthly compound interest, or reading lines from a log file—require loop constructs. The while loop is an entry-controlled (pre-test) loop that repeatedly executes a block of code as long as its specified condition remains true.
Figure 3: Decision and control flowcharts for while, do-while, for, and foreach loops in PHP.
Every properly constructed while loop requires three essential stages:
false.<?php
$count = 1; // 1. Initialization
// 2. Condition evaluated BEFORE each iteration
while ($count <= 5) {
echo "Iteration count: " . $count . "<br>";
$count++; // 3. Increment (Crucial: prevents infinite loop!)
}
?>
In professional PHP and MySQL programming, the while loop is the industry standard idiom for fetching database cursor rows:
<?php
// Simulating database rows returned from a query
$mockDbResult = [
["id" => 101, "name" => "Anil Kapoor", "branch" => "BCA"],
["id" => 102, "name" => "Deepa Nair", "branch" => "B.Tech CS"],
["id" => 103, "name" => "Manish Roy", "branch" => "BSc IT"]
];
$index = 0;
echo "<ul>";
// Loop continues until index exceeds the count
while ($index < count($mockDbResult)) {
$student = $mockDbResult[$index];
echo "<li>ID: " . $student['id'] . " | Name: " . $student['name'] . " (" . $student['branch'] . ")</li>";
$index++;
}
echo "</ul>";
?>
An infinite loop occurs when the condition never evaluates to false (e.g. omitting $i++). The script will run continuously until the server hits PHP's max_execution_time (usually 30 seconds) and crashes with a Fatal Error: Maximum execution time exceeded.
High-Frequency Exam Question:
Q: How many times will this loop execute: $i = 10; while ($i < 5) { echo $i; $i++; }?
A: Zero times. Because while is an entry-controlled loop, the condition 10 < 5 evaluates to false immediately on the first check, completely bypassing the loop body.
Exercise 15.1: Write a while loop to print the mathematical multiplication table of any given number (e.g. 7 × 1 = 7 up to 7 × 10 = 70).
Exercise 15.2: Write a while loop that calculates the sum of all even numbers between 1 and 50.