About us Privacy Disclaimer Contact us
FAQ Help Advertising Feedback
Home Sitemap Search Donate us

  Home > Computer & I'net > while/do while...

   Browse by title articles:
   What is hot:

Numbers - Random

Strings - Connecting

Strings - Pulling apart

if/elseif/else

switch/case

while/do while

Clickbank Security Using PHP
How to Protect Email Addresses in Textarea Fields From Harvesters and Spammers
Storage and re-use of images using PHP/GD - Part II
Text vs Pictures: Shedding Light on the Debate
Prev articles123456 7 89101112Next articles



while/do while


Computer & I'net articleswhile/do while

by David Stanley    



while is a loop. It will execute a block of coding for a specified amount of times.

<?php
while (condition) {
   do this block of coding;
   while the condition carries a true value;
   }
?>

Time for a quick example :
<?php
$test = 0;
while ($test < 10) {
   echo "$test is less than 10. <br />";
   $test++;
   }
?>

Example results :
0 is less than 10.
1 is less than 10.
2 is less than 10.
3 is less than 10.
4 is less than 10.
5 is less than 10.
6 is less than 10.
7 is less than 10.
8 is less than 10.
9 is less than 10.

At the end of each block execution, the while condition is tested again. If the condition holds a true value, the code block will be executed again. And so forth until the condition results as false. In this case, once $test equalled 10, the condition was false and the loop was broken.

If the value of the condition is false to begin with, the code block contained in the loop area is ignored. It will only be seen WHILE the condition is true.

do while is very similar to the above WHILE loop. It's main difference is the code block will be executed at least once before the condition statement is tested for a true or false value. If it is a true value, the loop will happen as before. If it is a false value, it will not perform the loop area any further.

<?php
do {
   do this block of coding;
   while the condition carries a true value;
   } while (condition);
?>

Here is that example again :
<?php
$test = 0;
do {
   echo "$test is less than 10. <br />";
   $test++;
   } while ($test < 10);
?>

And the result :
0 is less than 10.
1 is less than 10.
2 is less than 10.
3 is less than 10.
4 is less than 10.
5 is less than 10.
6 is less than 10.
7 is less than 10.
8 is less than 10.
9 is less than 10.

One of the main problems of using a DO WHILE loop, is that first execution. Try changing the value of $test to 15 :
15 is less than 10.

Not exactly correct is it? That happened because the loop was exectued for the first time before the condition was tested to be true or false. There very well may be times to need this effect. Just be sure which direction you want your loops to go in.




-----------------
Article by David Stanley. Visit his site http://www.htmlite.com. Reprinted with permission.





Student Loan




  Disclaimer | Privacy | Terms of useCopyright © 2004 Nice2know.com