PHP107
Flow Control - Iteration
So far, we have seen how to write sections of code where every line is executed, and where conditional statements determine which lines of code are executed using 'If' and 'Switch'. However, both type of code run from top to bottom and cease execution. Any 'real' application often requires that sections of code are repeated either a given number of times, or until certain criteria have been met.
PHP supports four different types of loop structures:
- while
- do … while
- for
- foreach
The first three types of loop are general purpose, and familiar to programmers in most languages, the last is specific to arrays.
while
This is probably the simplest loop structure to use. The loop continues to execute one or more instructions, whilst a condition remains true. The condition is checked first, and if found to be true the loop is executed while the condition remains true. If at the first check the condition is found to be false, the loop is never executed at all. It is essential that within the body of the loop a statement is capable of making the condition false. Without this, the loop will never cease to loop - an infinite loop. This is a common error when first writing loop structures in your code.
The following code prints the integers from 1 to 10 to screen, with a space between each.
<? $count = 1; while ($count < 11) { echo $count; echo " "; // increment the value of $count $count = $count + 1; } ?>
Note: - the value of $count is given an initial value (1) outside the loop, the condition for the loop is while $count has a value of less than 11, within the body of the loop a statement changes the value of $count - so that eventually the 'while' condition is no longer true and the loop ceases execution.
Do...While
The fundamental difference between this and the While loop concerns where in the process the condition is evaluated.
In a 'while' loop the condition is evaluated at the start of the loop, and if found not to be true the loop will not execute at all. Therefore, a 'while' loop may execute a number of times, or may not execute at all.
In a 'do...while' loop the statement which evaluates whether the loop needs to execute again is at the bottom of the block of code being executed. Therefore, this loop will execute at least once.
The following loop has the same functionality as the 'while' loop. Examine the code and see the difference.
<? $count = 1; do { echo $count; echo " "; $count = $count + 1; } while ($count <11); ?>
What is the output from the following loop ?
<? $count = 1000; do { echo $count; echo " "; $count = $count + 1; } while ($count <11); ?>
This produces the number 1001 as the body of the loop is executed once, then the condition fails (1001 is not less than 11), and the loop stops executing.
This structure is the same as 'Repeat Until …' found in many programming languages, and is not frequently used as it is unusual to have loop execute once even if a condition is false.
for
The syntax for this loop is the most complex, but it produces very tight code. The syntax is described below:
for (initial statement; condition for the loop to continue; what changes each time through) { // repeating code goes here; }
Note that there are three sections, each separated by a semi-colon.
If we write the same structure as used in the last two types of loops in the form of a 'for' loop, the code is:
<? for ($count=1; $count<11; $count=$count+1) { echo $count; echo " "; } ?>
The format used in this example is typical of many used in PHP, sets up a counter, checks the counter and increments the counter.
A Practical Example
One of the 'classic' examples for using loops is to produce a times table. We are going to develop the code for a web page which shows the timetables up to '12 times'. As we will see this requires a loop inside another loop. This is called a nested loop - and is not as complex as it sounds. First let's examine the logic of what is required, and then the actual PHP code.
We will use HTML for the basic page, headings etc and PHP for the loop's algorithms. Notice that a loop is required to count from 1 to 12, this is to first produce the one times table, then the two times table, the three times table etc.
With each iteration of the loop we need to pause and have a second loop from 1 to 12. To clarify, the first loop determines which times table we are generating. When this first loop reaches the first value we pause (at the value 1), and then have a second loop generate 1 times 1, 1 times 2, 1 times 3 ….1 times 12. At this point the second loop stops, as it has done its job. The first loop continues and move on to the value 2. We pause whilst the second loop starts again and generates 2 times 1, 2 times 2, 2 times 3, up to 2 times 12.
Again the second loop ceases execution, and we continue until eventually the first loop has reached the value 12.
The following is the code for this timetable. Read it carefully and ensure you understand how the loops work, in particular how they are nested to work in tandem. Type it up, ensure it works, and try amending the loop values to see the effect.
<html> <head> <title>The Times-Tables</title> </head> <body bgcolor="#ffffff"> <h1>The Times Tables</h1> <? // Go through each table for ($table=1; $table<13; $table++) { echo "<p><b>The " . $table . " Times Table</b>\n"; // Produce 12 lines for each table for ($counter=1; $counter<13; $counter++) { $answer = $table * $counter; // Is this an even-number counter? if ($counter % 2 == 0) { // Yes, so print this line in bold echo "<br><b>$counter x $table = ".$answer."</b>"; } else { // No, so print this in normal face echo "<br>$counter x $table = $answer"; } } } ?> </body> </html>
The only command which is not familiar to you at this stage is in the line:
if ($counter % 2 == 0)
This uses '%' to carry out a 'Div' function. It divides by 2 and looks at the 'remainder'. If the remainder is zero, having divided by two, it must be an even number (a useful technique, please note). The 'if' statement continues to print even numbers in bold, odd numbers in plain text.
The two loops are 'table' to determine which table is being calculated, and 'counter' which determines which number is being used in the table.
Exercises
Exercise 1
Produce a PHP script which counts from 1 to 100, and displays any numbers which have a factor of four (Hint: see how to use the 'Div' function above).
Exercise 2
Develop a page which on the first line writes a single '1', on the second line it should produce two '2's, on the third line it should write three '3's, and so on up to 9.
Exercise 3
Write a nested loop, which displays a representation of a chess board. It should have eight rows of eight columns, with each black square represented by a '[X]', and each white square represented by '[ ]. Again, the 'Div' function will help you decide which are black, and which are white squares. Remember, they alternate position after each row.
Exercise 4
Define a constant 'my_year' to the year of your birth. A loop should randomly generate numbers in the range 1900 to 1999, each number should be displayed on screen. This should continue until the number which has been randomly generated matches the year of your birth. The code to generate a random number in this range is given below:
<? $any_year = rand(1900, 1999); print $any_year; ?>
Exercise 5
Finally, for a bit of fun, write a PHP script which contains the single line
<? phpinfo(); ?>
Examine the environment variables, and research how you might use these to report back to a viewer of your web site, their IP address, which version of Operating System they are using, which Internet browser they are using etc.