SQL PHP HTML ASP JavaScript articles and free scripts to download If you are facing any problem in viewing this page, please tell us
 

Do while loop script


Loops are part of the programming structure in any language. We use this at different conditions and logics inside our script. We have discussed about while loop, now we will discuss about do while loop which is little different than while loop.

Difference in While Loop and do While loop
In while loop the condition is checked at the starting of the loop and if it is true then the code inside the loop is executed. This process is repeated till the condition becomes false. In case of do while loop the checking of condition is done at the end of the loop. So even if the condition is false, the script inside the loop is executed at least once. This is the basic difference between do while loop and while loop.

Let us start with one simple script with a do while loop to understand the syntax. Here the condition is checked at the end of the loop so the code inside the loop is executed for once.

$i=1;
do{
echo $i;
echo "<br>";
} while ($i > 1);


We can see in the above code that even though the $i value is 1 which is not true as per the condition set by the loop still the script will print value of $i once as the condition is checked at the end of the loop.

Like other loops we can use break statement to come out of the loop. In the code below we have tried to display number from 5 to 15, but as soon as the $i value reaches 11 the if condition becomes true and the break statement gets executed. So the loop stoops there and program execution comes out. Here is the code.

$i=5;
do{
echo $i;
echo "<br>";
$i=$i+1;
if($i>10){break;}
} while ($i < 15);

Further readings
Loops and program structure of PHP scripts
Checking variables by isset
switch
For Loop
if else condition checking
while loop
Do while loop
PHP beginners guide


Sections
PHP
JavaScript
ASP
HTML
SQL
Photoshop
Articles SEO
PHP Tutorials
Basic Loops
PHP Monthly Planner
PHP Introduction
Loops & structure
Array
Date & Time
Functions
Form Handling
File Handling
Math Functions
String Functions
GD Functions
Comment Posting
Content Management
PHP & Ajax
Popular Tutorials
Drop down list
File Upload
Signup script
Member Login
Line Graph
PHP MySQL Paging
PHP Calendar
Subscribe
Submit your email address and receive article and product notifications. Your email is safe with us.