Do while loop script

Do While loop in PHP

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

While Loop
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 or statements 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.
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. To compare between these two types of loops check this code.

echo $i; // Out put will be there
echo "<br>";
} while ($i > 1);
echo "<hr>";

$i=1; // we assigned a value to the variable again here
while($i > 1){
echo $i; // No output as loop will not be executed
echo "<br>";

Using break statement to stop execution of do while 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.
echo $i;
echo "<br>";
} while ($i < 15);

Show multiplication table

do {    
    echo $i*$j ."|";
} while($j<=10); 

Nested do while loops

Now we will keep one do while loop inside another outer do while loop and change $i value from 1 to 10. We will add a line break after each inner looping.
Multiplication table for 1 to 10
do { // Outer loop
do { // Inner loop   
    echo $i*$j ."|";
} while($j<=10); // end of inner loop
$j=1;  // reset value to 1
$i=$i+1; // increment 
echo "<br>"; // Line break
} while($i<=10) // end of outer loop 
Output is here
PHP Loops PHP While loop For loop Switch for matching code block in PHP
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net




    Post your comments , suggestion , error , requirements etc here

    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2023 All rights reserved worldwide Privacy Policy Disclaimer