0
0
PHPprogramming~5 mins

Do-while loop execution model in PHP

Choose your learning style9 modes available
Introduction

A do-while loop runs a block of code at least once, then repeats it while a condition is true.

When you want to run code first, then check if it should repeat.
When you need to ask a user for input and repeat until valid.
When you want to process something at least once before stopping.
When the condition depends on the code that runs inside the loop.
Syntax
PHP
do {
    // code to run
} while (condition);

The code inside do { } runs first, before the condition is checked.

The loop repeats only if the condition after while is true.

Examples
This prints numbers 1 to 3 because the loop runs first, then checks if count is less or equal to 3.
PHP
<?php
$count = 1;
do {
    echo "Count is $count\n";
    $count++;
} while ($count <= 3);
?>
This prints "Hello" once because the condition is false at start, but the loop runs once before checking.
PHP
<?php
$x = 5;
do {
    echo "Hello\n";
} while ($x < 3);
?>
Sample Program

This program prints numbers from 1 to 5. It runs the code first, then checks if the number is still 5 or less to continue.

PHP
<?php
$number = 1;
do {
    echo "Number: $number\n";
    $number++;
} while ($number <= 5);
?>
OutputSuccess
Important Notes

Unlike a while loop, a do-while loop always runs the code block at least once.

Remember to update variables inside the loop to avoid infinite loops.

Summary

A do-while loop runs code first, then checks the condition.

It is useful when the code must run at least once.

Use it when the condition depends on the code inside the loop.