PHP Chapter 5 (Programming Loops)

PHP For Loops

So what’s a loop then? A loop is something that goes round and round. If I told you to move a finger around in a loop, you’d have no problem with the order (unless you have no fingers!) In programming, it’s exactly the same. Except a programming loop will go round and round until you tell it to stop. You also need to tell the programme two other things - where to start your loop, and what to do after it’s finished one lap (known as the update expression).
You can programme without using loops. But it’s an awful lot easier with them. Consider this.
You want to add up the numbers 1 to 4: 1 + 2 + 3 + 4. You could do it like this:
$answer = 1 + 2 + 3 + 4;
print $answer;
Fairly simple, you think. And not much code, either. But what if you wanted to add up a thousand numbers? Are you really going to type them all out like that? It’s an awful lot of typing. A loop would make life a lot simpler. You use them when you want to execute the same code over and over again.
We'll discuss a few flavours of programming loops, but as the For Loop is the most used type of loop, we'll discuss those first.

For Loops

Here’s a PHP For Loop in a little script. Type it into new PHP script and save your work. Run your code and test it out.
<?PHP
$counter = 0;
$start = 1;
for($start; $start < 11; $start++) {
$counter = $counter + 1;
print $counter . "<BR>";
}
?>
How did you get on? You should have seen the numbers 1 to 10 printed on your browser page.
The format for a For Loop is this:
for (start value; end value; update expression) {
}
The first thing you need to do is type the name of the loop you’re using, in this case for. In between round brackets, you then type your three conditions:
Start Value
The first condition is where you tell PHP the initial value of your loop. In other words, start the loop at what number? We used this:
$start = 1;
We’re assigning a value of 1 to a variable called $start. Like all variables, you can make up your own name. A popular name for the initial variable is the letter i . You can set the initial condition before the loop begins, like we did:
$start = 1;
for($start; $start < 11; $start++) {
Or you can assign your loop value right in the For Loop code:
for($start = 1; start < 11; start++) {
The result is the same – the start number for this loop is 1

End Value
Next, you have to tell PHP when to end your loop. This can be a number, a Boolean value, a string, etc. Here, we’re telling PHP to keep going round the loop while the value of the variable $start is Less Than 11.
for($start; $start < 11; $start++) {
When the value of $start is 11 or higher, PHP will bail out of the loop.

Update Expression
Loops need a way of getting the next number in a series. If the loop couldn’t update the starting value, it would be stuck on the starting value. If we didn’t update our start value, our loop would get stuck on 1. In other words, you need to tell the loop how it is to go round and round. We used this:
$start++
In a lot of programming language (and PHP) the double plus symbol (++) means increment (increase the value by one). It’s just a short way of saying this:
$start = $start + 1
You can go down by one (decrement) by using the double minus symbol (--), but we won’t go into that.
So our whole loop reads “Starting at a value of 1, keep going round and round while the start value is less than 11. Increase the starting value by one each time round the loop.”
Every time the loop goes round, the code between our two curly brackets { } gets executed:
$counter = $counter + 1;
print $counter . "<BR>";
Notice that we’re just incrementing the counter variable by 1 each time round the loop, exactly the same as what we’re doing with the start variable. So we could have put this instead:
$counter ++
The effect would be the same. As an experiment, try setting the value of $counter to 11 outside the loop (it’s currently $counter = 0). Then inside the loop, use $counter- - (the double minus sign). Can you guess what will happen? Will it crash, or not? Or will it print something out? Better save your work, just in case!
To get more practice with the For Loop, we'll write a little Times Table programme.


A PHP Times Table Programme

In this section, we'll write a times table programme to illustrate how for loops work.
There's a script called timesTable.php amongst the files you downloaded (in the scripts folder). When loaded into the browser, it looks like this:
There's a script called timesTable.php amongst the files you downloaded (in the scripts folder.). When loaded into the browser, it looks like this:
Times Table Programme
What we're going to do is to get the values from the textboxes and create a Times Table proramme. When the button is clicked, the output will be something like this:
In other words, when the button is clicked we'll print the Times Table to the page. You can have a different Times Table, depending on what values you enter in the textboxes. To make a start with the coding, move on to the next part.

Code for a PHP Times Table

The code for the Times Table in the previous page uses a For Loop. The Start for the loop will come from the Start Number textbox, and the end of the loop will come from the End Number textbox. Here's the code in full (without the HTML):
<?PHP
$times = 2;
if (isset($_POST['Submit1'])) {
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
for($start; $start <= $end; $start++) {
$answer = $start * $times;
print $start . " multiplied by " . $times . " = " . $answer . "<BR>";
}
}
?>

Code Explanation
We need all those numbers from the textboxes on the form, so we start with:
$times = 2;
if (isset($_POST['Submit1'])) {
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
}
The first line just puts a value in the variable called $times . This is so that the "Multiply By" textbox will have a default value when the page is loaded.
Next we use the isset( ) function again, just to check if the user clicked the Submit button. This is exactly the same as you saw in the last section.
To get the values from the textboxes, we use the following:
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
Again, this is code you met in the last section. You just assign the values from the textboxes to the new variables using $_POST[]. In between the square brackets, we've typed the NAME of the HTML textboxes. So this gives us the values that the user entered on the form. Next comes out For Loop:
for($start; $start <= $end; $start++) {
$answer = $start * $times;
}
Let's look at that first line again:
for($start; $start <= $end; $start++) {
So we have a starting value for our loop, an end value, and an update expression. The starting value is coming from the variable called $start. This will be whatever number the user entered in the first textbox. The default is 1. Look at the end value, though:
$start <= $end
The end value is when the value in the variable called $start is less than or equal to the value held in the variable called $end. This works because we're increasing the value of $start each time round the loop. The variable called $end is a fixed value, and comes from the textbox on the form.
The last part of the loop code is the update expression. This tells PHP to increase the value of $start each time round the loop:
$start++
The double plus symbol (++) means "add 1 to the number held in $start".
And that's the essence of for loops: provide a start value, an end value, and how you want to update each time round the loop.
The code inside the for loop, however, the code that gets executed each time round the loop, is this:
$answer = $start * $times;
Remember, the variable $times holds the times table, the 2 times table by default. This is being multiplied by whatever is inside the variable $start. Each time round the loop, $start will have a different value – first 1, then 2, then 3, etc. The answer is then stored in the variable that we called $answer. So it's really doing this:
$answer = 1 * 2;
$answer = 2 * 2;
$answer = 3 * 2;
etc
Finally, we displayed the result to the page like this:
print $start . " multiplied by " . $times . " = " . $answer . "<BR>";
This is just concatenation. See if you can work out what all the parts do!
And that’s it – your very own times table generator. If you have children, show them the programme you wrote. They’ll be very impressed and tell you how brilliant you are. Children are like that.
Of course, your programme is not perfect, which I’m sure the children will discover. Especially if they enter a 10 as the start number and a 1 as the end number. Why doesn't it print anything out? Anything you can do to trap this error? Another if statement somewhere, perhaps?

PHP While Loops

Instead of using a for loop, you have the option to use a while loop. The structure of a while loop is more simple than a for loop, because you’re only evaluating the one condition. The loop goes round and round while the condition is true. When the condition is false, the programme breaks out of the while loop. Here’s the syntax for a while loop:
while (condition) {
statement
}
And here’s some code to try. All it does is increment a variable called counter:
$counter = 1;
while ($counter < 11) {
print (" counter = " . $counter . "<BR>");
$counter++;
}
The condition to test for is $counter < 11. Each time round the while loop, that condition is checked. If counter is less than eleven then the condition is true. When $counter is greater than eleven then the condition is false. A while loop will stop going round and round when a condition is false.
If you use a while loop, be careful that you don’t create an infinite loop. You’d create one of these if you didn’t provide a way for you condition to be evaluated as true. We can create an infinite loop with the while loop above. All we have to do is comment out the line where the $counter variable is incremented. Like this:
$counter = 1;
while ($counter < 11) {
print (" counter = " . $counter . "<BR>");
//$counter++;
}
Notice the two forward slashes before $counter++. This line will now be ignored. Because the loop is going round and round while counter is less than 11, the loop will never end – $counter will always be 1.
Here’s a while loop that prints out the 2 times table. Try it out in a script.
$start = 1;
$times = 2;
$answer = 0;
while ($start < 11) {
$answer = $start * $times;
print ($start . " times " . $times . " = " . $answer . "<BR>");
$start++;
}
The while loop calculates the 2 times tables, up to a ten times 2. Can you see what’s going on? Make sure you understand the code. If not, it’s a good idea to go back and read this section again. You won’t be considered a failure. Honest!

PHP Do ... While loops

This type is loop is almost identical to the while loop, except that the condition comes at the end:
do
statement
while (condition)
The difference is that your statement gets executed at least once. In a normal while loop, the condition could be met before your statement gets executed.
Don’t worry too much about do … while loops. Concentrate on For loops and While loops. But there is another type of loop that comes in handy - the For Each loop. First, a quick word about thebreak statement.

The PHP break statement

There are times when you need to break out of a loop before the whole thing gets executed. Or, you want to break out of the loop because of an error your user made. In which case, you can use the break statement. Fortunately, this involves nothing more than typing the word break. Here’s some not very useful code that demonstrates the use of the break statement:
$TeacherInterrupts = true;
$counter = 1;
while ($counter < 11) {
print(" counter = " + $counter + "<BR>");
if ($TeacherInterrupts == true) {
break;
}
$counter++;
}
Try the code out and see what happens.
Ok, that's enough of loops. For now. In the next section, we'll take a look at what arrays are, and how useful they can be. (Yes, there'll be loops!)

Comments