0
0
PhpHow-ToBeginner · 3 min read

How to Use While Loop in PHP: Syntax and Examples

In PHP, a while loop repeats a block of code as long as a given condition is true. The syntax is while (condition) { /* code */ }, where the condition is checked before each iteration.
📐

Syntax

The while loop in PHP runs the code inside its block repeatedly as long as the condition is true.

  • condition: A test that returns true or false.
  • code block: The statements to run each time the condition is true.

The condition is checked before each loop. If it is false at the start, the code block does not run.

php
while (condition) {
    // code to execute
}
💻

Example

This example prints numbers from 1 to 5 using a while loop. It shows how the loop runs repeatedly while the condition is true.

php
<?php
$counter = 1;
while ($counter <= 5) {
    echo $counter . "\n";
    $counter++;
}
?>
Output
1 2 3 4 5
⚠️

Common Pitfalls

Common mistakes with while loops include:

  • Forgetting to update the variable in the condition, causing an infinite loop.
  • Using a condition that is always false, so the loop never runs.
  • Modifying the loop variable incorrectly inside the loop.

Always ensure the condition will eventually become false to stop the loop.

php
<?php
// Wrong: Infinite loop because $i is never changed
$i = 1;
while ($i <= 3) {
    echo $i . "\n";
    // Missing $i++ here
}

// Correct: Increment $i to avoid infinite loop
$i = 1;
while ($i <= 3) {
    echo $i . "\n";
    $i++;
}
?>
Output
1 2 3
📊

Quick Reference

Tips for using while loops in PHP:

  • Use while when you want to repeat code until a condition changes.
  • Always update the variable in the condition inside the loop.
  • Use break; to exit the loop early if needed.
  • Remember the condition is checked before running the loop body.

Key Takeaways

A while loop runs code repeatedly while its condition is true.
Always update the loop variable inside the loop to avoid infinite loops.
The condition is checked before each loop iteration.
Use while loops for repeating tasks when the number of repetitions is not fixed.
Use break to exit a while loop early if needed.