PHP while loop


In this lesson, you will learn how to use while loop in PHP. A ‘while loop’ let you run the same set of a statement(s) repeatedly until a condition is met.

Introduction to ‘while loop’ in PHP

The syntax

while( expression ){

//statement
}

The expression in the while loop is checked at the start of the first iteration; if the value is evaluated as true, the parser will execute the while code block. The loop will continue to execute until encounters the false Boolean value in the expression. If the expression is empty or evaluated as true every time, the loop will become infinite and will be executed indefinitely.

In this last lesson, we learned about for loop which can also be written in while loop.

<?php
for ($num = 1; $num <= 10; $num ++) { 
echo "$num \n"; 
} 
?>

The ‘for loop’ example above can be written using the ‘while loop’.

<?php
$num = 1;
while($num <= 10){
echo "$num \n"; 
$num ++;
}
?>

How it works

The flowchart below shows how while loop works in PHP.

while loop Flowchart

Example I of while loop in PHP

<?php

$i = 0;
while ($i < 5){
echo $i + 1 . "<br>";
$i++;
}

?>

Example II of while loop in PHP

<?php

define('MAX',10); 
$count = 1; 
while($count <= MAX){
echo " {$count}<br/>";
$count++;
}

?>

Do While Loop in PHP

Do while loop is a variant of while loop in PHP. The only difference is the execution of the first iteration. In while loop it will always check the condition first and then execute or break the loop code but in do while, PHP will execute the code block at least for once, even if the condition is false. In ‘do while’ loops, PHP will check the condition at the end of every iteration, whereas I in a while loop, the condition is checked right after the start of the iteration.

The syntax

do{
//statements
}while( expression )

Example of do while loop in PHP

<?php

$i = 10;
do{
echo "$i is"." <br>";
}
while($i < 5);

?>

In this example, 10 is stored in a variable $i. The condition in ‘do while’ loop checks if the value in $i is less than 5. Do while will execute the echo statement once and at the end of the iteration, it will evaluate the condition which is Boolean false. The loop will break as it has met the false condition. The above code will print 10 only.

PHP for Loop Tutorial Home PHP ForEach Loop
Tutorials Panel

About Tutorials Panel

programming tutorial and source code for Software Engineers and developers. https://twitter.com/TutorialsPanel

View all posts by Tutorials Panel →