Skip to content

PHP While Loops

Loops are used to execute the same block of code repeatedly, as long as a certain condition is met. They are fundamental constructs for automating repetitive tasks.

PHP provides several types of loops to handle different scenarios:

  • while - Executes a block of code as long as the specified condition evaluates to true. The condition is checked before each iteration.
  • do...while - Executes a block of code once, and then repeats the loop as long as the specified condition evaluates to true. The condition is checked after each iteration.
  • for - Executes a block of code a specified number of times. Typically used when the number of iterations is known beforehand.
  • foreach - Executes a block of code for each element in an array or object. Ideal for iterating over collections.

This chapter focuses on the while and do...while loops.

The while loop is the simplest type of loop in PHP. It iterates as long as its condition remains true.

while (condition) {
// Code to be executed inside the loop
}

How it works:

  1. The condition is evaluated.
  2. If the condition is true, the code block inside the loop is executed.
  3. After the code block executes, control returns to step 1 (the condition is evaluated again).
  4. If the condition is false, the loop terminates, and execution continues with the statement immediately following the loop.

Example: Counting from 1 to 5

<?php
$counter = 1;
while ($counter <= 5) {
echo "The counter is: {$counter}<br>";
$counter++; // Increment the counter - crucial to avoid an infinite loop!
}
echo "Loop finished!";
?>

Output:

The counter is: 1<br>
The counter is: 2<br>
The counter is: 3<br>
The counter is: 4<br>
The counter is: 5<br>
Loop finished!

Important: Ensure that the condition within a while loop will eventually become false. Otherwise, you will create an infinite loop, which can freeze your script or server.

The do...while loop is similar to the while loop, but with a key difference: the condition is checked after the code block is executed. This guarantees that the code block runs at least once, even if the condition is initially false.

do {
// Code to be executed inside the loop
} while (condition);

How it works:

  1. The code block inside the loop is executed.
  2. The condition is evaluated.
  3. If the condition is true, control returns to step 1 (the code block executes again).
  4. If the condition is false, the loop terminates.

Example: Running code at least once

<?php
$attempts = 0;
$maxAttempts = 3;
do {
$attempts++;
echo "Attempting connection (Attempt: {$attempts})...<br>";
// Simulate a connection attempt that might fail
$success = ($attempts >= 2); // Let's pretend it succeeds on the 2nd try
if ($success) {
echo "Connection successful!<br>";
break; // Exit the loop if successful
} elseif ($attempts >= $maxAttempts) {
echo "Connection failed after {$maxAttempts} attempts.<br>";
}
} while (!$success && $attempts < $maxAttempts);
?>

Example where the loop runs only once:

<?php
$x = 6;
do {
echo "This will run once. The number is: {$x} <br>";
$x++;
} while ($x <= 5); // Condition is false immediately after the first run
echo "Loop finished!";
?>

Output:

This will run once. The number is: 6 <br>
Loop finished!

Use do...while when you need to ensure the loop body executes at least one time, regardless of the condition’s initial state.

The for loop and the foreach loop offer different ways to control iteration and will be covered in subsequent chapters.