|Friday, 12 March 2010|
Page 1 of 3
A basic introduction to the while, while do and for loops.
The loop is the programming construct which enables programmers to repeat a block of instructions. Without loops programs would be very limited. In everyday life we tend not to notice the loops or repeats contained in a list of instructions simply because we are sophisticated, but in a program you have to be precise.
There are two different types of loop - conditional and enumeration.
For example, if the instructions in a recipe say stir until the liquid thickens then this is a conditional loop but if they say stir ten times then this is an enumeration loop.
In PHP conditional loops are implemented using the while or do-while instruction and enumeration loops are implemented using the for or the foreach instruction. Let's start with the conditional loop because, while the enumeration loop is conceptually simpler, the for instruction can be difficult.
A conditional loop simply repeats a block of instructions until some condition is satisfied. Hidden in this simple description are a large number of possible variations on the basic theme and hence many complexities. The art with all good programming is to keep what you write simple and understandable.
The most basic of PHP loops is the while loop:
which repeats the statement over and over again until the condition becomes false. The condition is evaluated each at the start of each repeat. As in the case of other control instructions you can extend the statement to be repeated to a list of statements by using curly brackets to create a compound statement.
This first stores 1000 in the variable $a and then starts the while loop. It evaluates the condition $a>1 which is true and so the body of the while loop is obeyed sending "1000 <br/>" to the web page and dividing a$ by 10 and storing the result, i.e. 100, back into $a. At this point the end of the loop has been reached and control passes back to the start of the loop where the condition is once again evaluated and as 100 is still greater than 1 the body of the loop is repeated sending "100 <br/> " to the web page. this time the value of $a is 10 and when the loop repeats the condition is still true and the body of the loop is obeyed once more sending "10 <br/>" to the web page. This time when the condition is evaluated $a contains 1 and $a>1 is false causing the loop to end and control to pass to the next instruction following the loop. Notice that if you think of evaluating the condition as being the start of the loop when the condition is false the body of the loop is skipped.
If you take your finger and point to the instructions as they are obeyed you will find that you go round in small circles - hence loop:
Notice that the "shape" of the loop seems to have two parts - the looping back and the jumping out of the loop to the instruction following the loop.
Do conditional loops exist?
You might have noticed that this is a poor example of a strictly conditional loop. You can predict before the loop begins that it will repeat exactly three times. Surely this is an enumeration loop in disguise? In many cases a conditional loop can be easily converted into an enumeration loop but there are situations where it is just simpler to write the loop using a condition and others where it is in principle impossible.
For example, suppose you write a loop that processes some data from a data file or database then it would be difficult, if not impossible, to work out how many times the loop would repeat because the answer would depend on data in the file not yet read. The same is generally true. Whenever a loop stopping depends on data that comes from an external source then you have little choice but to write a conditional loop.
In many other cases, however, it is just easier to write a conditional rather than an enumeration loop. In all cases you should use the form that is most natural for the task in hand and always try to make your program reflect the way you think about the task. If you think that the task is to repeat something a number of times then write an enumeration loop. If you think that the task is to repeat something until a condition is reached then write a conditional loop.
Ask yourself the question "what is the smallest number of times the body of a while loop is executed?".
The answer is that the condition is tested at the start of the loop and the loop body is only executed if the condition is true. What this means is that the body of the loop can be skipped the first time the loop is encountered so it could be that it is never executed at all. That is, if the condition is false when the while loop starts the body of the loop isn't obeyed. Hence the body of the loop can be executed zero or more times.
The do while loop on the other hand has the test that terminates the loop at the end of the loop. That is:
executes the instructions, then evaluates the condition, if it is true it "loops back" to repeat the instructions again and so on...
For example, the previous while loop can be written as a do while loop as:
In this case there is no difference in what is sent to the web page because the condition is true when loop starts and the position of the loop exit point makes no difference. However, if you trace the flow of control with your finger you should get a shape something like:
Now you can clearly see that the difference between the two loops is that the exit point is at the start of the loop in the case of a while loop and at the end of the loop in the case of a do-while loop.
How does this translate into the way the loops behave? Ask yourself what is the minimum number of times the body of a do-while loop is obeyed? If the condition is false when the loop starts and is still false when the body has been executed then the do-while loop will exit immediately, i.e. after one execution of the body of the loop. A do-while loop repeats things once or more.
For an example, admittedly contrived, of where this makes a difference try:
The first example, the while loop doesn't send anything to the web page because the condition is immediately false and the loop body is skipped. In the second example, the do-while loop, the value "1 <br/>" is sent to the web page because the loop body is executed before the condition is tested. As the value of $a when the condition is evaluated is 1/10 the condition is false and the loop terminates after one execution of the loop body.
When you first learn about conditional loops the difference between the while and the do-while seems mysterious and almost unnecessary but in practice conditional loops really do mostly fall into these two categories- exit at the start or exit at the end.
When you are writing a PHP program it is also usually very natural to think about when the condition should be tested and whether something should be done as a result or you doing something and then testing a condition.
Notice that it is true that you really don't need the do-while at all. If you want to you can convert a do-while into a while loop simply by explicitly writing out the body of the loop once before the while loop starts. This way you ensure that the loop body will be obeyed at least once.
The do-while may not be necessary but its use can make a program a great deal simpler and you should always aim to use whichever loop makes your program easier to understand.
Finally in case you are wondering - yes loops can have exit points at other positions than just at the start or at the end. This is a more advanced topic and discussed in another article. However, it is worth saying that some programmers are of the opinion that loops with exit points anywhere other than the start or end are to be avoided as they are unnecessarily complicated.
There is a sense in which the while and do-while loops are the fundamental building blocks of the loopy universe in the sense that all other loops can be built using them.
|Last Updated ( Monday, 15 March 2010 )|