How to Implement while and do...while Loops in PHP
This article explains the purpose of loops in programming and provides detailed PHP examples of while and do...while constructs, including syntax, step‑by‑step code samples, and important behavior notes such as condition evaluation timing.
When writing code you often need to execute the same block repeatedly; loops allow this without duplicating code.
PHP while loop
The while loop runs its block as long as a given condition evaluates to true.
In PHP the available loop statements are:
while – executes the block while the condition is true
do...while – executes the block once, then repeats while the condition is true
for – repeats a block a specified number of times
foreach – iterates over each element of an array
PHP while loop syntax
<code>while (condition) {</code><code> // code to execute</code><code>}</code>Example: initialize $x = 1 , then increment it while it is less than or equal to 5.
<code><?php</code><code>$x = 1;</code><code>while ($x <= 5) {</code><code> echo "这个数字是:$x <br>";</code><code> $x++;</code><code>}</code><code>?></code>PHP do...while loop
The do...while loop executes its block once before checking the condition; if the condition is true, it repeats.
Syntax:
<code>do {</code><code> // code to execute</code><code>} while (condition);</code>Example: start with $x = 1 , output the value, increment, and continue while $x <= 5 .
<code><?php</code><code>$x = 1;</code><code>do {</code><code> echo "这个数字是:$x <br>";</code><code> $x++;</code><code>} while ($x <= 5);</code><code>?></code>Note that a do...while loop always runs its body at least once, even if the condition is false on the first check.
Another example sets $x = 6 ; the loop runs once, then the condition ( $x <= 5 ) fails, so it stops.
<code><?php</code><code>$x = 6;</code><code>do {</code><code> echo "这个数字是:$x <br>";</code><code> $x++;</code><code>} while ($x <= 5);</code><code>?></code>php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.