Home >>PHP Tutorial >PHP Do While Loop

PHP Do While Loop

Do while loop in PHP

The do...while Loop executes the statement once and then check the condition.

Syntax

	do
	{
	 code to be executed;
  	}
	while (condition);
	

Eg

<?php
	
$i=1;
	
do
	 
 {
	  
echo "The number is " . $i . "<br>";
	 
 $i++;
	  
}
	
while ($i<=5);
  
?>
Output
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

In the above example,
variable $i hold value="1". first execute the statement inside do.
after that it check while condition($i<=5).
So the given statements execute 5 times.


Write a program to display table of given number.

<?php
	
@$tab=$_GET['tab'];
	
$i=1;
	
do
	 
 {
	  	
$t=$tab*$i;
	 	
echo $t." ";
	    	
$i++;

}
	
while ($i<=10);		
 
?>

 <body>
 	
<form>
	  
Enter Your table<input type="text" name="tab"><br/>
	  
 <input type="submit" value="Table">
	
</form>
 
</body>


Output
10 20 30 40 50 60 70 80 90 100
Enter your table

In the above example,
Create text-box and a button using HTML script. Logic is performed inside PHP script.
First we collect the value entered by user using $_GET. $i hold value=1.
to print the table of 10. ($t=$tab*$i) this condition multiply the entered value with $x(initial value) value is increment after every iteration.
While check ($i<=10). so the while( ) loop executes the statement 10 times.
Output will generate table of 10.


Nested do - while

Write a program to display more than one table at a time.

<?php
	
$n=1;
	
$i=0;
	
$t=0;
	
	
do
	  
{
	  	
do
		
{
		  
$i++;
		  	  
$t=$i*$n;	  
		  
echo $t;
			  
while($i<=10)
		 
}	 
	  	
$i=0; 
	  	
$n++; 
	 	
while ($n<=10); 
	  
}	
 
?>

In the above example,
we display more than one table, nested do while loop is used.
Declare three variable $n hold vale="1"
$i hold value="0"
$t hold value="0"


Popular Tutorials