0
0
PHPprogramming~5 mins

While loop execution model in PHP

Choose your learning style9 modes available
Introduction

A while loop repeats a set of instructions as long as a condition is true. It helps do tasks multiple times without writing the same code again.

When you want to keep asking a user for input until they give a valid answer.
When you want to repeat an action until a certain number is reached.
When you want to process items in a list but don't know how many items there are.
When you want to keep running a game loop until the player quits.
Syntax
PHP
<?php
while (condition) {
    // code to repeat
}
?>

The condition is checked before each loop. If it is true, the code inside runs.

If the condition is false at the start, the code inside the loop never runs.

Examples
This prints numbers 1 to 3. The loop stops when $count becomes 4.
PHP
<?php
$count = 1;
while ($count <= 3) {
    echo "Count is $count\n";
    $count++;
}
?>
This loop runs only once because $keepGoing becomes false inside the loop.
PHP
<?php
$keepGoing = true;
while ($keepGoing) {
    echo "Running loop\n";
    $keepGoing = false;
}
?>
Sample Program

This program uses a while loop to print numbers from 1 to 5. It starts at 1 and adds 1 each time until it reaches 5.

PHP
<?php
// Print numbers from 1 to 5 using while loop
$number = 1;
while ($number <= 5) {
    echo "Number: $number\n";
    $number++;
}
?>
OutputSuccess
Important Notes

Make sure the condition will eventually become false, or the loop will run forever.

You can change variables inside the loop to control when it stops.

Summary

A while loop repeats code while a condition is true.

The condition is checked before each repetition.

Use it when you don't know how many times you need to repeat in advance.