HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP While Loop

Loops are used to execute the same block of code repeatedly as long as a certain condition is true. The while loop is the simplest type of loop in PHP, checking its condition before each iteration.


The while Loop Syntax

As long as the condition evaluates to true, the code within the braces will keep running.

<?php
    $x = 1;

    while($x <= 5) {
        echo "The number is: $x <br>";
        $x++; // This is CRITICAL!
    }
?>

Breaking Down the Loop

A functional while loop usually has three main parts:

  • The Initializer: $x = 1; — Sets the starting point.
  • The Condition: $x <= 5 — The loop runs only if this is TRUE.
  • The Increment: $x++; — Updates the counter so the condition eventually becomes FALSE.
Infinite Loop Warning: If you forget to update your variable (like $x++), the condition will always be true, and your browser/server might crash!

Example: Counting by Tens

You can change the update logic to skip numbers or calculate differently.

<?php
    $x = 0;

    while($x <= 100) {
        echo "Percentage: $x% <br>";
        $x += 10;
    }
?>
Technical Note: If the condition is false from the very start, the code inside the while loop will never execute.
Pro Tip: Use while loops when you don't know exactly how many times the code needs to run (e.g., reading rows from a database until no rows are left).

Key Points to Remember

  • The while loop checks the condition first, then runs the code.
  • It repeats as long as the condition is TRUE.
  • You must update the variable inside the loop to avoid infinite loops.
  • The loop will never run if the condition is false at the beginning.
  • Loops are essential for tasks involving repeated data or calculations.