← Back to Chapters

PHP While Loop

? PHP While Loop

? Quick Overview

The while loop in PHP allows repeated execution of a code block as long as a given condition remains true. It is especially helpful when the number of iterations is not known in advance.

? Key Concepts

  • The condition is checked before each loop iteration
  • If the condition is false initially, the loop will not run
  • Loop variables must be updated inside the loop

⚙️ Syntax / Theory

? View Code Example
// Basic structure of a PHP while loop
while (condition) {
    // code to be executed
}

? Code Example

? View Code Example
// PHP while loop counting from 1 to 5
<?php
$count = 1;
while ($count <= 5) {
    echo "Count is: $count<br>";
    $count++;
}
?>

? Live Output / Explanation

Output

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

The loop checks the condition before each iteration. Once $count becomes greater than 5, the condition fails and the loop stops executing.

? Interactive Example

Adjust the values below to see how the logic gate behaves. This simulator mimics how PHP processes the loop.

Waiting...
?

Current Value of $i

> Click Run to start...

? Use Cases

  • Reading database records one by one
  • Processing user input until a condition is met
  • Generating dynamic HTML lists

✅ Tips & Best Practices

  • Always update the loop variable inside the loop
  • Ensure the condition will eventually become false
  • Use break to exit the loop early if needed

? Try It Yourself

  • Create a file named while_loop.php
  • Write a while loop to print even numbers from 1 to 20
  • Modify the condition to reverse the loop