PHP Question: While And Do While Looping

16th May 2011


What does the $count variable equal after each of these loops?

  1. // Loop 1 - while
  2. $count = 0;
  4. while ($count
  6. // Loop 2 - do while
  7. $count = 0;
  9. do {
  10. ++$count;
  11. } while ($count
  17. Answer
  18. The $count variable will equal 0 after loop 1 and 1 after loop 2. This is because when a while loop is run the condition is looked at before the first iteration, exiting if it equals false. Conversely, a do while loop will run the condition after the first iteration. This means that a do while loop will always run at least once, even if the condition equals false.
  20. In the above code the first loop will not run because the result of the comparison is false. The second loop will run once, incrementing the $count value by 1, and then exit after testing the comparison
  22. This is is an important distinction between how while and do while loops work and can be useful in certain circumstances. For example, a while loop is a handy way of replacing an if statement and a for loop with a single while statement.
  24. If the condition initially equals true then both loops will work in the same way. For example, if we made both loop conditions exit when the count is greater than 10, and run the code again, the output of both loops would equal 10.



The first loop will return 0 and the second one as 1. reason being, while, first checks the condition and fails and do while, first executes it and then checks the condition. 

Sirish (Tue, 05/17/2011 - 21:57)

Add new comment

The content of this field is kept private and will not be shown publicly.