The while
loop - Loops through a block of code as long as the specified condition is true.
The PHP while Loop
The while
loop executes a block of code as long as the specified condition is true.
Syntax
while [condition is true] {
code to be executed;
}
Examples
The example below displays the numbers from 1 to 5:
Example
Try it Yourself »
Example Explained
- $x = 1; - Initialize the loop counter [$x], and set the start value to 1
- $x
Try it Yourself »
Example Explained
- $x = 0; - Initialize the loop counter [$x], and set the start value to 0
- $x
Try it Yourself »
Note: In a
do...while
loop the condition is tested AFTER executing the statements within the loop. This means that thedo...while
loop will execute its statements at least once, even if the condition is false. See example below.This example sets the $x variable to 6, then it runs the loop, and then the condition is checked:
Example
Try it Yourself »
[PHP 4, PHP 5, PHP 7, PHP 8]
while
loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of awhile
statement is:The meaning of a
while
statement is simple. It tells PHP to execute the nested statement[s] repeatedly, as long as thewhile
expression evaluates totrue
. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement[s], execution will not stop until the end of the iteration [each time PHP runs the statements in the loop is one iteration]. If thewhile
expression evaluates tofalse
from the very beginning, the nested statement[s] won't even be run once.Like with the
if
statement, you can group multiple statements within the samewhile
loop by surrounding a group of statements with curly braces, or by using the alternate syntax:while [expr]: statement ... endwhile;
The following examples are identical, and both print the numbers 1 through 10:
razvan_bc at yahoo dot com ¶
2 months ago
assuming you want to have another way to archieve
then yo have this:Dan Liebner ¶
1 year ago
While loops don't require a code block [statement].
mparsa1372 at gmail dot com ¶
1 year ago
The example below displays the numbers from 1 to 5:
This example counts to 100 by tens:er dot sarimkhan786 at gmail dot com ¶
6 years ago
simple pyramid pattern program using while loop
// or alternatively you can use:
How do I run a while loop in PHP?
The PHP do-while loop is guaranteed to run at least once. The PHP do-while loop is used to execute a set of code of the program several times..Chủ Đề