PHP Question: While And Do While Looping

Question

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

// Loop 1 - while
$count = 0;

while ($count < 0) {
    ++$count;
}
// Loop 2 - do while
$count = 0;

do {
    ++$count;
} while  ($count < 0);









 

Answer

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.

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

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.

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.

Comments

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. 

Permalink

I've got a question about the do while order, what will happen if you rotate it to while do? I am sorry if it sounds like a stupid question I admit I am a beginner and really would like to learn, thank you.

Permalink

Hi Daniel,

It's fine to ask questions, especially if you're learning!

So I'm assuming you mean converting the structure to this:

while ($count < 0) {
  ++$count;
} do

This results in a syntax error as PHP doesn't know what to do with the "do" at the end of the statement. In PHP there is a while loop and a do-while loop, but not a while-do loop.

The question in this post is meant to show the differences between while and do-while, showing that the code in the do-while loop is run at least once, even if the outcome of the while check is false.

I hope that helps a little?

Name
Philip Norton
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.