The while
loop in PHP executes a block of code repeatedly as long as a specified condition remains true. It is useful when the number of iterations is unknown in advance.
Syntax of a PHP While Loop
<?php while (condition) { // Code to be executed } ?>
📝 Example 1: Simple While Loop
Prints numbers from 1 to 5.
<?php $i = 1; while ($i <= 5) { echo "Number: $i <br>"; $i++; } ?>
📝 Example 2: While Loop with Decrement
Prints numbers from 5 to 1.
<?php $i = 5; while ($i >= 1) { echo "Countdown: $i <br>"; $i--; } ?>
📝 Example 3: While Loop with User Input
Keep asking for user input until they enter "stop" (Assuming input is simulated).
<?php $input = ""; while ($input != "stop") { $input = readline("Enter something (type 'stop' to exit): "); echo "You entered: $input <br>"; } ?>
🎯 When to Use a While Loop?
- When the number of iterations is unknown.
- When continuously checking for a condition.
- For reading data until the end of a file or user input.
📝 Practice Time!
Modify the examples above and experiment with different conditions to understand how while loops work.