Skip to content

Latest commit

 

History

History
154 lines (106 loc) · 3.01 KB

File metadata and controls

154 lines (106 loc) · 3.01 KB

PHP While Loops

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.


Syntax

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.


Example: Basic while Loop

$count = 0;

while ($count <= 10) {
    echo $count . ",";
    $count++;
}

Output:

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>

Output:

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>

Output:

0,1,2,3,4,FIVE,6,7,8,9,10,
11

Key Notes

  • The loop counter must be modified inside the loop to avoid infinite loops.

  • Use if statements inside the loop to add custom logic for specific values.

  • After the loop, $count reflects the value after the last successful condition check.


Use Cases for while Loops

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.

Security Considerations

  • Guard against infinite loops. A while whose condition never becomes false hangs 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_time and memory_limit as a backstop, but treat them as defence-in-depth — correct loop logic is the primary control.

Related