while / do-while
Among iteration constructs, those used when the number of iterations is not known in advance are the『while』statement and the『do-while』statement. In『PHP』, these two constructs let you write processing that continues looping as long as a condition is met.
Syntax
// while statement: executes the block repeatedly while the condition is true
while (condition) {
// processing executed repeatedly while the condition is true
}
// do-while statement: executes the block at least once, then evaluates the condition
do {
// processing executed at least once regardless of the condition
} while (condition);
Difference Between while and do-while
| Syntax | When the condition is evaluated | Minimum executions |
|---|---|---|
| while | Before the block executes (pre-condition check). | 0 times. If the condition is false from the start, the block never executes. |
| do-while | After the block executes (post-condition check). | 1 time. The first iteration always runs regardless of the condition. |
Use『while』when the condition might be『false』from the start. Use『do-while』when you want the loop body to execute at least once before deciding whether to continue.
Loop Control
| Syntax | Description |
|---|---|
| break | Terminates the loop immediately. Skips all remaining iterations once the condition is met. |
| break n | Specifying a number exits that many levels of nested loops at once. |
| continue | Skips the remaining processing of the current iteration and proceeds to the next. The condition is re-evaluated. |
| continue n | Specifying a number proceeds to the next iteration of the loop n levels up in nested loops. |
Sample Code
while_basic.php
<?php
// A Jujutsu Kaisen sorcerer continuously activates a technique while consuming cursed energy
$characterName = "Itadori Yuji";
$cursedEnergy = 100; // remaining cursed energy
// Continues activating as long as cursed energy is 20 or more
while ($cursedEnergy >= 20) {
echo $characterName . ": technique activated (remaining energy: " . $cursedEnergy . ")\n";
$cursedEnergy -= 25; // each activation costs 25
}
echo $characterName . ": cursed energy depleted (remaining: " . $cursedEnergy . ")\n";
Running the code produces the following output:
php while_basic.php Itadori Yuji: technique activated (remaining energy: 100) Itadori Yuji: technique activated (remaining energy: 75) Itadori Yuji: technique activated (remaining energy: 50) Itadori Yuji: technique activated (remaining energy: 25) Itadori Yuji: cursed energy depleted (remaining: 0)
do_while_basic.php
<?php
// do-while: the menu is always displayed at least once, then continues based on the selection
// The body executes at least once even if the condition is false from the start
$characterName = "Gojo Satoru";
$attemptCount = 0;
$maxAttempts = 3;
do {
$attemptCount++;
echo $characterName . ": technique expansion #" . $attemptCount . "\n";
} while ($attemptCount < $maxAttempts);
echo "Total expansions: " . $attemptCount . "\n";
// Example where the body executes once even when the condition is false from the start
echo "\n--- When the condition is false from the start ---\n";
$count = 10;
do {
echo "This block always executes (count = " . $count . ")\n";
$count++;
} while ($count < 5); // false from the start, but executes once
Running the code produces the following output:
php do_while_basic.php Gojo Satoru: technique expansion #1 Gojo Satoru: technique expansion #2 Gojo Satoru: technique expansion #3 Total expansions: 3 --- When the condition is false from the start --- This block always executes (count = 10)
while_file_read.php
<?php
// Practical pattern for file reading with while
// Reads one line at a time until feof() returns true
$filename = "jujutsu_members.txt";
$fp = fopen($filename, "r");
if ($fp === false) {
echo "Could not open the file\n";
exit(1);
}
echo "--- Sorcerer Member List ---\n";
// Reads one line at a time until the end of the file is reached
while (!feof($fp)) {
$line = fgets($fp);
if ($line !== false) {
echo trim($line) . "\n"; // remove the trailing newline and output
}
}
fclose($fp); // always close the file
jujutsu_members.txt
Itadori Yuji Fushiguro Megumi Kugisaki Nobara Gojo Satoru
Running the code produces the following output:
php while_file_read.php --- Sorcerer Member List --- Itadori Yuji Fushiguro Megumi Kugisaki Nobara Gojo Satoru
while_pdo_cursor.php
<?php
// Practical pattern for PDO cursor processing with while
// fetch() returns an array while records exist, and false when they run out
$dsn = "mysql:host=localhost;dbname=jujutsu;charset=utf8mb4";
$pdo = new PDO($dsn, "user", "password");
$stmt = $pdo->query("SELECT name, grade FROM sorcerers ORDER BY grade ASC");
echo "--- Sorcerer List (by grade) ---\n";
// Process repeatedly until fetch() returns false
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'] . " (grade " . $row['grade'] . ")\n";
}
Running the code produces the following output:
php while_pdo_cursor.php --- Sorcerer List (by grade) --- Gojo Satoru (grade Special) Geto Suguru (grade Special) Nanami Kento (grade 1) Fushiguro Toji (grade 1) Itadori Yuji (grade 1)
do_while_retry.php
<?php
// do-while is also suited for retry processing
// Takes advantage of the fact that the first attempt always executes once
$characterName = "Fushiguro Megumi";
$maxRetries = 3;
$attempt = 0;
$success = false;
do {
$attempt++;
echo $characterName . ": Ten Shadows Technique attempt #" . $attempt . "\n";
// Simulation where success occurs on the third attempt
if ($attempt === 3) {
$success = true;
echo $characterName . ": Shikigami summoning succeeded\n";
} else {
echo $characterName . ": Summoning failed, retrying\n";
}
} while (!$success && $attempt < $maxRetries);
if (!$success) {
echo $characterName . ": Maximum retry count reached\n";
}
Running the code produces the following output:
php do_while_retry.php Fushiguro Megumi: Ten Shadows Technique attempt #1 Fushiguro Megumi: Summoning failed, retrying Fushiguro Megumi: Ten Shadows Technique attempt #2 Fushiguro Megumi: Summoning failed, retrying Fushiguro Megumi: Ten Shadows Technique attempt #3 Fushiguro Megumi: Shikigami summoning succeeded
Common Mistakes
Common Mistake 1: Infinite loop (condition is always true, or forgetting to increment the loop counter)
If the condition expression of a while statement is always true, or if the variable that influences the condition is not updated inside the loop, an infinite loop results. The mistake of forgetting to update the condition-affecting variable inside the loop is especially common.
ng_while_infinite.php
<?php
// Forgetting to decrement $cursedEnergy keeps the condition always true
$characterName = "Itadori Yuji";
$cursedEnergy = 100;
while ($cursedEnergy >= 20) {
echo $characterName . ": technique activated (remaining energy: " . $cursedEnergy . ")\n";
// $cursedEnergy -= 25; is missing, causing an infinite loop
if ($cursedEnergy > 1000) break; // emergency stop
}
Running the code produces the following output:
php ng_while_infinite.php Itadori Yuji: technique activated (remaining energy: 100) Itadori Yuji: technique activated (remaining energy: 100) Itadori Yuji: technique activated (remaining energy: 100) ...(never ends)
Always update the variable that affects the condition inside the loop body.
ok_while_infinite.php
<?php
$characterName = "Itadori Yuji";
$cursedEnergy = 100;
while ($cursedEnergy >= 20) {
echo $characterName . ": technique activated (remaining energy: " . $cursedEnergy . ")\n";
$cursedEnergy -= 25; // always update inside the loop
}
echo $characterName . ": cursed energy depleted (remaining: " . $cursedEnergy . ")\n";
Running the code produces the following output:
php ok_while_infinite.php Itadori Yuji: technique activated (remaining energy: 100) Itadori Yuji: technique activated (remaining energy: 75) Itadori Yuji: technique activated (remaining energy: 50) Itadori Yuji: technique activated (remaining energy: 25) Itadori Yuji: cursed energy depleted (remaining: 0)
Common Mistake 2: Forgetting the semicolon in do-while (Parse error)
The『while (condition)』at the end of a do-while statement requires a semicolon (;). This rule does not exist for for or while statements, so it is easy to forget. A missing semicolon causes a Parse error.
ng_dowhile_semicolon.php
<?php
$characterName = "Gojo Satoru";
$count = 0;
do {
$count++;
echo $characterName . ": technique expansion #" . $count . "\n";
} while ($count < 3) // semicolon is missing
Running the code produces the following output:
php ng_dowhile_semicolon.php Parse error: syntax error, unexpected end of file, expecting ";" in ...
Add a semicolon at the end of the while condition in do-while.
ok_dowhile_semicolon.php
<?php
$characterName = "Gojo Satoru";
$count = 0;
do {
$count++;
echo $characterName . ": technique expansion #" . $count . "\n";
} while ($count < 3); // do not forget the semicolon
Running the code produces the following output:
php ok_dowhile_semicolon.php Gojo Satoru: technique expansion #1 Gojo Satoru: technique expansion #2 Gojo Satoru: technique expansion #3
Common Mistake 3: Unexpected behavior when a function with side effects is used in the condition
Any expression can be written in a while condition, but when a function with side effects (DB access, file reading, etc.) is called directly in the condition, the last fetch or read before the loop ends can be executed one extra time as a waste. Also, the number of condition evaluations may be higher than expected, which can affect performance.
ng_while_side_effect.php
<?php
// fgets() is called on every condition evaluation (one extra call occurs at EOF when the loop ends)
$fp = fopen("jujutsu_members.txt", "r");
while ($line = fgets($fp)) {
// The loop ends when $line becomes false (EOF), but
// fgets() itself executes once when reading EOF for the termination check
echo trim($line) . "\n";
}
fclose($fp);
Running the code produces the following output:
php ng_while_side_effect.php Itadori Yuji Fushiguro Megumi Kugisaki Nobara Gojo Satoru
This pattern works, but be aware that fgets() is called one extra time when it detects EOF. For reading the entire file, consider file() or file_get_contents().
ok_while_side_effect.php
<?php
// Reading the entire file as an array (fewer lines than the fgets while approach)
$lines = file("jujutsu_members.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
echo $line . "\n";
}
Running the code produces the following output:
php ok_while_side_effect.php Itadori Yuji Fushiguro Megumi Kugisaki Nobara Gojo Satoru
Summary
The『while』statement is a pre-condition loop that evaluates the condition first. If the condition is『false』from the start, the block never executes. It is suited for processing where the number of iterations is variable and the block may not need to run at all.
The『do-while』statement is a post-condition loop that evaluates the condition after the block runs.The block always runs at least once regardless of the condition value.It is suited for situations such as user input validation or retry processing—"execute first, then decide whether to continue." Note that the semicolon at the end of the closing『} while (condition);』is easy to forget.
For file reading, the standard pattern is to combine『fopen() / fclose()』with a loop that continues until『feof()』returns『true』. For database cursor processing, the common pattern is to loop until PDO's『fetch()』returns『false』. For PDO usage, see also『PDO (database connection)』. When the number of iterations is explicit,『for statement』makes the intent of the code clearer.
If you find any errors or copyright issues, please contact us.