Mastering while and do...while Loops
Master PHP while and do...while loops — unknown iteration counts, database rows, file reading, menus, and when to choose each loop type.
Mastering while and do...while Loops
Introduction
In the previous lesson, you learned how to use the for loop when you already know how many times a block of code should execute.
But what if you don't know the number of iterations?
For example:
- Read records from a database until no more records exist.
- Keep asking a user to enter a valid password.
- Read a file until the end of the file.
- Process messages from a queue until it's empty.
- Retry an API call until it succeeds or reaches a maximum retry limit.
In these situations, a for loop isn't always the best choice.
Instead, PHP provides two more looping constructs:
- while
- do...while
These loops continue executing as long as a condition remains true.
Understanding when to use each loop is an important skill for every PHP developer.
What is a while Loop?
A while loop repeatedly executes a block of code as long as a specified condition evaluates to true.
Unlike a for loop, a while loop does not require initialization or increment expressions inside its syntax.
This makes it more flexible when the number of iterations is unknown.
Syntax
while (condition) {// Code to execute}
PHP follows this sequence:
- Check the condition.
- If the condition is true, execute the loop.
- Return to step 1.
- Stop when the condition becomes false.
Flow Diagram
Start ↓ Check Condition ↓ True? ↓ ↓ Yes No ↓ ↓ Execute End ↓ Back to Condition
The condition is checked before every iteration.
Example 1: Print Numbers
<?php$i = 1;while ($i <= 5) {echo $i . "<br>";$i++;}
Output:
1 2 3 4 5
Notice that the counter is updated inside the loop.
Step-by-Step Execution
Initial value:
$i = 1;
Iteration 1
1 <= 5 → true Print 1 Increment to 2
Iteration 2
2 <= 5 → true Print 2 Increment to 3
This continues until:
6 <= 5 → false
The loop ends.
Example 2: Countdown
<?php$count = 5;while ($count >= 1) {echo $count . "<br>";$count--;}echo "Liftoff!";
Output:
5 4 3 2 1 Liftoff!
Example 3: Print Even Numbers
<?php$number = 2;while ($number <= 20) {echo $number . " ";$number += 2;}
Output:
2 4 6 8 10 12 14 16 18 20
Real-World Example: Reading Database Records
Imagine you execute a database query.
Each call to fetch() returns one row until there are no more rows.
<?phpwhile ($row = fetchNextRecord()) {echo $row["name"] . "<br>";}
This continues until fetchNextRecord() returns false or null.
This pattern is common in database-driven applications.
Real-World Example: Login Attempts
<?php$attempts = 1;$maxAttempts = 3;while ($attempts <= $maxAttempts) {echo "Login Attempt " . $attempts . "<br>";$attempts++;}
Output:
Login Attempt 1 Login Attempt 2 Login Attempt 3
Real-World Example: Reading a File
<?phpwhile (!feof($file)) {$line = fgets($file);echo $line;}
The loop continues until the end of the file is reached.
This is a practical use of while because the number of lines isn't known in advance.
Infinite while Loops
Be careful. This code never stops.
<?phpwhile (true) {echo "Running...";}
Or:
<?php$i = 1;while ($i <= 5) {echo $i;}
The second example never updates $i. Since the condition always remains true, the loop runs forever.
Always ensure that the loop variable changes appropriately.
When Should You Use while?
Use a while loop when:
- The number of iterations is unknown.
- Reading data from files.
- Processing database records.
- Waiting for user input.
- Polling an external service.
- Consuming messages from a queue.
If you already know the exact number of iterations, a for loop is often a better choice.
What is a do...while Loop?
A do...while loop is very similar to a while loop.
However, there is one important difference.
A do...while loop executes its block at least once, even if the condition is false.
Syntax
do {// Code} while (condition);
Notice that the condition is checked after executing the loop body.
Flow Diagram
Start ↓ Execute Code ↓ Check Condition ↓ True? ↓ ↓ Yes No ↓ ↓ Repeat End
Example 1: Basic Usage
<?php$i = 1;do {echo $i . "<br>";$i++;} while ($i <= 5);
Output:
1 2 3 4 5
Example 2: Condition Starts as False
<?php$i = 10;do {echo "Executed Once";} while ($i < 5);
Output:
Executed Once
Even though the condition is false, the code executes one time.
This is the defining feature of a do...while loop.
Real-World Example: Menu System
Imagine a command-line application.
The menu should appear at least once.
<?phpdo {echo "1. Login\n";echo "2. Exit\n";$choice = getUserChoice();} while ($choice != 2);
The user always sees the menu before deciding whether to exit.
Real-World Example: Password Prompt
<?phpdo {$password = getPassword();} while ($password !== "secret123");
The prompt appears at least once and repeats until the correct password is entered.
while vs do...while
| Feature | while | do...while |
|---|---|---|
| Condition Checked | Before execution | After execution |
| Executes at Least Once? | No | Yes |
| Best For | Unknown iterations | User interaction, menus, prompts |
Which One Should You Use?
Use while when the loop should execute only if the condition is true.
Use do...while when the code must execute at least once before checking the condition.
Performance Considerations
There is almost no noticeable performance difference between while and do...while.
Choose the loop based on readability and the problem you're solving—not because of performance.
In most applications, database queries, file operations, and network requests have a much greater impact on performance than the choice of loop.
Best Practices
Initialize Variables Clearly
Always initialize loop variables before entering the loop.
$count = 1;
This makes your code easier to understand.
Update the Loop Variable
Never forget to update the variable that controls the loop.
$count++;
Without this, the loop may never end.
Keep Conditions Simple
Instead of writing long, complicated conditions, break complex logic into smaller helper functions when appropriate.
Readable code is easier to debug and maintain.
Avoid Heavy Operations Inside Loops
If a value doesn't change, calculate it before the loop instead of during every iteration.
This reduces unnecessary work.
Use Meaningful Variable Names
Instead of:
while ($x < 100)
Prefer:
while ($pendingOrders > 0)
Descriptive names make business logic easier to follow.
Common Mistakes
Forgetting to Increment
$i = 1;while ($i <= 5) {echo $i;}
This creates an infinite loop. Always update the loop variable.
Using the Wrong Loop Type
If you know the exact number of iterations, a for loop is usually clearer than a while loop. Choose the loop that best matches the problem.
Complex Conditions
Avoid conditions like:
while (($a < 10 && $b > 5) || ($c == 20 && !$done))
Such conditions are difficult to read and maintain.
Break them into smaller pieces when possible.
Modifying the Condition Unexpectedly
Changing multiple variables that control the loop inside different branches can make the code difficult to reason about. Keep loop logic predictable.
Hands-on Exercise
Create a PHP program that:
- Prints numbers from 1 to 50 using a while loop.
- Prints only odd numbers.
- Counts backward from 20 to 1.
- Calculates the sum of numbers from 1 to 100.
- Displays the multiplication table of 9.
- Uses a do...while loop to print a welcome message once.
- Simulates three login attempts using a while loop.
- Builds a simple menu using a do...while loop.
Try solving these exercises on your own before checking any solutions. The more you practice, the more natural loops will become.
Summary
The while and do...while loops are powerful tools for handling situations where the number of iterations isn't known beforehand.
A while loop checks its condition before executing the code, making it suitable for tasks that may not need to run at all.
A do...while loop executes the code at least once, making it ideal for menus, prompts, and user interactions.
Understanding when to choose each loop will help you write cleaner, more efficient, and more maintainable PHP applications.
Key Takeaways
- Use a while loop when the number of iterations is unknown.
- The while condition is checked before each iteration.
- Use a do...while loop when the code must run at least once.
- Always update loop variables to avoid infinite loops.
- Keep loop conditions simple and readable.
- Choose the loop type based on the problem, not personal preference.
- Avoid expensive operations inside loops whenever possible.
What's Next?
In Mastering the foreach Loop, you'll learn how to iterate through indexed arrays, associative arrays, multidimensional data, API responses, and collections like a professional PHP developer.
Continue at /learn/php/mastering-foreach.