PHP While Loops
Loops let you repeat code multiple times. The while
loop is PHP's
simplest loop - it keeps executing as long as a condition remains true. Perfect
when you don't
know in advance how many iterations you'll need.
While Loop Syntax
The while loop checks the condition before each iteration:
<?php
while (condition) {
// Code to repeat
// Make sure condition eventually becomes false!
}
?>
| Step | What Happens |
|---|---|
| 1. Check | Evaluate the condition |
| 2. Execute (if true) | Run the code block |
| 3. Repeat | Go back to step 1 |
| 4. Exit (if false) | Continue after the loop |
Click Run to execute your code
Basic While Loop Examples
<?php
// Counting up
$i = 1;
while ($i <= 5) {
echo "Number: $i\n";
$i++; // Don't forget this!
}
// Counting down
$countdown = 5;
while ($countdown > 0) {
echo "$countdown... ";
$countdown--;
}
echo "Liftoff!\n";
// Processing until empty
$queue = ["Task 1", "Task 2", "Task 3"];
while (count($queue) > 0) {
$task = array_shift($queue); // Remove first element
echo "Processing: $task\n";
}
?>
false.
Update a variable inside the loop, or use break to exit.
Do-While Loop
The do-while loop checks the condition after each iteration, guaranteeing at least one execution:
<?php
do {
// Code to repeat (runs at least once)
} while (condition); // Note the semicolon!
?>
Click Run to execute your code
While vs Do-While
| Feature | while | do-while |
|---|---|---|
| Condition check | Before loop body | After loop body |
| Minimum iterations | 0 (may never run) | 1 (always runs once) |
| Use when | May not need to run at all | Must run at least once |
| Syntax ending | } |
} while (...); |
<?php
$value = 100;
// While: Won't execute (condition false initially)
while ($value < 10) {
echo "While: $value\n";
$value++;
}
// Do-while: Executes once despite false condition
do {
echo "Do-while: $value\n";
$value++;
} while ($value < 10);
?>
Practical Use Cases
Reading File Lines
<?php
$file = fopen("data.txt", "r");
while (($line = fgets($file)) !== false) {
echo $line;
}
fclose($file);
?>
Database Result Processing
<?php
$result = $mysqli->query("SELECT name FROM users");
while ($row = $result->fetch_assoc()) {
echo "User: " . $row['name'] . "\n";
}
?>
Retry Logic with Backoff
<?php
$maxRetries = 3;
$attempt = 0;
$success = false;
while ($attempt < $maxRetries && !$success) {
$attempt++;
echo "Attempt $attempt... ";
// Simulate operation that might fail
$success = (rand(1, 3) === 1);
if ($success) {
echo "Success!\n";
} else {
echo "Failed. Retrying...\n";
sleep(1); // Wait before retry
}
}
if (!$success) {
echo "All $maxRetries attempts failed.\n";
}
?>
Infinite Loops
Sometimes you intentionally want an infinite loop, exiting with
break:
<?php
// Infinite loop pattern
while (true) {
$input = readline("Enter command (quit to exit): ");
if ($input === "quit") {
break; // Exit the loop
}
echo "You entered: $input\n";
}
echo "Goodbye!\n";
?>
- The loop variable is modified inside the loop
- There's a
breakcondition that can be reached - Set
max_execution_timein production to prevent runaway scripts
Alternative Syntax
While loops have an alternative syntax for templates:
<?php $items = ["Apple", "Banana", "Cherry"]; $i = 0; ?>
<ul>
<?php while ($i < count($items)): ?>
<li><?= $items[$i] ?></li>
<?php $i++; ?>
<?php endwhile; ?>
</ul>
Common Mistakes
1. Forgetting to update the loop variable
<?php
$i = 1;
// โ WRONG: Infinite loop! $i never changes
while ($i <= 5) {
echo $i;
// Missing: $i++
}
// โ
CORRECT: Increment the counter
while ($i <= 5) {
echo $i;
$i++;
}
?>
2. Off-by-one errors
<?php
$items = [1, 2, 3, 4, 5];
$i = 0;
// โ WRONG: <= causes index out of bounds
while ($i <= count($items)) { // 0,1,2,3,4,5 (6 iterations!)
echo $items[$i]; // Error on last iteration
$i++;
}
// โ
CORRECT: Use < for zero-indexed arrays
while ($i < count($items)) { // 0,1,2,3,4 (5 iterations)
echo $items[$i];
$i++;
}
?>
3. Missing semicolon in do-while
<?php
// โ WRONG: Missing semicolon causes syntax error
do {
echo "Hello";
} while (false) // Missing semicolon!
// โ
CORRECT: Always end with semicolon
do {
echo "Hello";
} while (false);
?>
Exercise: Number Guessing Game
Task: Create a simple number guessing game simulation.
Requirements:
- Generate a random target number between 1 and 10
- Simulate guesses until correct or max attempts reached
- Give "too high" or "too low" hints
- Track number of attempts
- Display success or failure message
Show Solution
<?php
$target = rand(1, 10);
$maxAttempts = 5;
$attempts = 0;
$won = false;
// Simulated guesses
$guesses = [5, 3, 7, 8, 6, 4, 9, 2, 10, 1];
echo "Guess a number between 1 and 10!\n";
echo "(Secret number: $target)\n\n";
while ($attempts < $maxAttempts && !$won) {
$guess = $guesses[$attempts];
$attempts++;
echo "Attempt $attempts: Guessing $guess... ";
if ($guess === $target) {
$won = true;
echo "Correct!\n";
} elseif ($guess < $target) {
echo "Too low!\n";
} else {
echo "Too high!\n";
}
}
echo "\n";
if ($won) {
echo "You won in $attempts attempt(s)!\n";
} else {
echo "Game over! The number was $target.\n";
}
?>
Summary
- while: Checks condition first, may run 0 times
- do-while: Checks condition after, always runs at least once
- Loop variable: Always update it to prevent infinite loops
- break: Exit the loop immediately
- Infinite loops: Use
while (true)withbreak - Use case: Best when iterations depend on runtime conditions
What's Next?
While loops are great for unknown iteration counts. Next, let's explore For Loops - the go-to choice when you know exactly how many times to repeat!
Enjoying these tutorials?