PHP While Loop


 

PHP While Loop

In this tutorial we will study about while loop in PHP. How to write while loop is discussed in this tutorial. Examples in this tutorial will make it more clear.

In this tutorial we will study about while loop in PHP. How to write while loop is discussed in this tutorial. Examples in this tutorial will make it more clear.

While Control Structure:

While is the simplest form of loop. While loop checks the condition first and if it returns true then it proceeds and allows to execute the codes written within the block and keep executing the codes until the condition becomes false, sometimes it fails to meet the condition to stop, and become infinite loop. While loop is also known as pre-test loop.

Basic format of while loop is as follows:

while(condition)
	expressions;

We can have nested while loop, we can use the alternative structure in while like we have done in if control structure as given in the following example:

Example:

<?php

$i=1;

while($i<11){

echo "Value of \$i is $i <br/>";

$i++;} 

?>

Output:

Value of $i is 1
Value of $i is 2
Value of $i is 3
Value of $i is 4
Value of $i is 5
Value of $i is 6
Value of $i is 7
Value of $i is 8
Value of $i is 9
Value of $i is 10

Example:

<?php

$a=10;

while($a>0):

echo $a--."<br/>";

endwhile;

?>

Output:

10
9
8
7
6
5
4
3
2
1

Ads