A while loop executes a block of code as long as a specified condition is true. It's ideal when the number of iterations isn't known in advance.
while (condition) {
// code to be executed
}-
The condition is evaluated before each iteration.
-
If the condition is
true, the block runs. -
If the condition becomes
false, the loop ends.
$count = 0;
while ($count <= 10) {
echo $count . ",";
$count++;
}0,1,2,3,4,5,6,7,8,9,10,
whileloops.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>While Loops</title>
</head>
<body>
<?php
$count = 0;
while ($count <= 10 ) {
echo $count . ",";
$count++;
}
echo "<br />";
echo $count;
?>
</body>
</html>0,1,2,3,4,5,6,7,8,9,10,
11
whileloops2.php (With Conditional)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>While Loops</title>
</head>
<body>
<?php
$count = 0;
while ($count <= 10 ) {
if ($count == 5){
echo "FIVE,";
} else {
echo $count . ",";
}
$count++;
}
echo "<br />";
echo $count;
?>
</body>
</html>0,1,2,3,4,FIVE,6,7,8,9,10,
11
-
The loop counter must be modified inside the loop to avoid infinite loops.
-
Use
ifstatements inside the loop to add custom logic for specific values. -
After the loop,
$countreflects the value after the last successful condition check.
| Use Case | Why Use while? |
|---|---|
| Reading input until EOF | You don't know how many inputs there will be |
| Waiting for a condition | Such as file creation or user input |
| Looping until dynamic condition met | Great for database record processing, etc. |
-
Guard against infinite loops. A
whilewhose condition never becomesfalsehangs the request, tying up a PHP worker and enabling a Denial-of-Service (DoS) condition. Always ensure the loop counter or exit condition is updated on every iteration. -
Bound loops driven by untrusted input. If the number of iterations depends on user-supplied data (e.g. a request parameter, uploaded file size, or record count), cap it with an explicit maximum so an attacker cannot force excessive iterations and exhaust CPU or memory.
-
Set resource limits. Rely on
max_execution_timeandmemory_limitas a backstop, but treat them as defence-in-depth — correct loop logic is the primary control.
- Control-Structures — control-flow overview
- For-Loops — alternative looping construct
- Continue-and-Break-Loops — altering loop flow
- Secure PHP Development — language hub