Quantcast
Channel: #! code - PHP Questions
Viewing all articles
Browse latest Browse all 10

PHP Question: While And Do While Looping

$
0
0

Question

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

1
2
3
4
5
6
// Loop 1 - while$count=0; 
while($count<0){    ++$count;}
1
2
3
4
5
6
// 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.

Category: 

Viewing all articles
Browse latest Browse all 10

Trending Articles