Control Structures, part II
In a previous video, we looked at using logical branching structures to control which statements get executed in your code and which get skipped, depending on your data. In this video we look at one more way to control your code’s execution path – looping.
Personally, I’m a huge fan of looping code. One of my pet peeves is when I come across someone else’s code where they’re doing the same thing over and over for line after line after line, where they clearly could have just used a loop to get the same result.
There are actually 4 different looping structures that PHP supports. The first is called the ‘for’ loop. Here’s the basic syntax:
for($var1 = 0; $var1 < 20; $var1++) {
//code goes here
}
That’s the typical example anyway. The ‘for’ declaration is followed by a 3-part expression in parenthesis. The way this particular setup will work is by setting a variable called $var1 to be 0, incrementing it by 1 each time it goes through the loop, and when it’s no longer less than 20, the loop ends. So, this loop will run 20 times, unless some instruction inside the loop causes $var1’s value to change in some other way, or else exit the loop prematurely.
While going through the loop, the code has access to the current value of the $var1 variable.
Here’s a simple example:
for($var1 = 0; $var1 < 20; $var1++) {
echo ‘I am on loop number ‘ . $var1 . ‘<br>’;
}
{show output}
And you see it’s just 20 lines in ascending order.
Now, a word of caution about loops. If your condition can never be false, then you’re going to get an infinite loop. In practical terms, that’s not quite as bad in PHP as in most other languages. The PHP process gets an execution time limit, 30 seconds by default, and once it takes longer than that to finish, the server kills it. But still, you should never have an infinite loop on purpose.
Before we move on, I want to take a closer look at the three statements inside the for declaration. The first is just a base condition that gets run once just before the loop starts.
The second statement is like the code in your ‘if’ declarations. If it’s true, then the code will run. If it’s false, then the loop is finished and the code execution resumes on the line immediately after your code block.
The final statement is going to be run once at the end of each loop.
A fairly common use for the ‘for’ loop in most languages that have it is iterating over arrays. Assuming your array has integer indexes, you just use the loop counter variable, in this case $var1 as your key to access each value in turn. However, in PHP, the language gives you a specialized control structure just for looping over arrays, called the ‘foreach’ loop. And that’s what we’re going to look at next here.
So, starting with an array ‘$array1’, I use the special syntax below to iterate over it, and assign each of the array’s values to the variable $var1 in turn. So, as I’m going through the loop, my code will be able to act on every value in the array just by referencing $var1.
$array1 = range(0, 19);
foreach($array1 as $var1) {
echo ‘I am on loop number ‘ . $var1 . ‘<br>’;
}
{show output}
The range function is just one of those handy ones built into PHP. In this case, I give it a minimum and maximum value, and it gives me an array with each integer in that range as its values.
Foreach has another way of being invoked though, and that lets you get both the keys, and the values:
foreach($array1 as $key => $value) {
echo “Key $key has value $value<br>”;
}
{show output}
This is particularly useful with associative arrays, where both the key and the value are significant. It’s also something you can’t do just iterating over an array in a for loop.
Now, occasionally, you’ll want to actually change the values of an array as you iterate over them. It’s not possible to change the keys, but to change the values, you use a special operator – the single &:
foreach($array1 as &$value) {
$value *= 2;
}
unset($value);
foreach($array1 as $key => $value) {
echo “Key $key has value $value<br>”;
}
So, this bit of code is going to double each value in the array. The call to unset at the end there is important because after the final loop, $value is still connected to the last value in the array. Using unset just unlinks that variable from the array, and avoids the risks of weird or unexpected behavior. But we talk about variable references in a later video, so I won’t go into more detail here.
{show output}
By the end of loop, the values in $array1 will all be doubled.
The next two loop types I want to introduce you to are the while and do while loops. These are sort of like for loops in a sense, except they only have the conditional expression. There’s no initializer and no expression that gets run with each loop. With the while loop, so long as its condition evaluates to true, it will continue to run. The code within the block is responsible for changing the data such that the condition no longer evaluates to true. Here’s a simple example:
$var1 = 10;
while($var1 > 0) {
echo ‘The current value is ‘ . $var1 . ‘<br>’;
$var1–;
}
{show output}
While $var1 is greater than 0, it prints out its value and then decreases it by 1. Eventually the while condition is no longer true and the code exits the loop. In the case of the while loop, if the condition is false to begin with, the loop will never execute. The difference with the do while loop is that you are guaranteed to run your loop at least one time. Instead of evaluating the condition, and then running the code if it’s true, it runs the code, and then checks the condition to determine whether to run it again.
{change $var1 = 10 to $var1 = 0}
{show output}
See? As a while loop, it didn’t run. Now if we change it to a do while loop, all we do is place the ‘while’ statement, with its conditional expression, after the closing brace. And we put the word ‘do’ up here in front of the opening brace:
{modify loop}
{show output}
The loop code ran once, and then since the condition was false, it didn’t run again.
The last thing I’m going to show you when it comes to loops is how to use the special ‘break’ and ‘continue’ statements. We already got a look at the break statement in the context of ‘switch’, and in the case of loops it does the same thing. When your script hits a break statement for whatever reason, it exits whatever loop (or switch statement) it happens to be in:
$var1 = 10;
while($var1 > 0) {
echo ‘The current value is ‘ . $var1 . ‘<br>’;
if($var1 == 5) {
break;
}
$var1–;
}
If you’re inside of two or more loops, and need to break out of all of them, you can use the break statement followed by the number of loops and switches you want to break out of:
$x = 32;
for($i = 0; $i <10; $i++) {
for($j=10; $j > 0; $j–) {
if($j*$i == $x) {
break 2;
}
}
}
echo “($i, $j)”;
On the other hand, sometimes you don’t want to exit a loop entirely, but you do want to skip to the next iteration. Well, in that case continue is what you need. In the case of a switch statement, since there is no iteration taking place, it will perform exactly the same as a break. But in a loop, it simply halts the current iteration and skips ahead to the next one, if one exists. If there are no further iterations to perform, the loop simply ends:
for($i = 0; $i<30; $i++) {
if($i % 4 == 3) {
continue;
}
echo ‘I am on iteration #’ . $i . ‘<br>’;
}
Like break, continue can also be used with multiple loops. Suppose I have a couple of nested for loops. If the inner loop hits ‘continue 2’, then it’ll break out of that loop completely, but then begin the next iteration of the outer loop.
That concludes the lesson on control structures. They’re a little tricky the first time you see them, but they’re indispensable in good coding.
February 11 2010 11:47 am | Basics and PHP Programming Basics and PHP tutorial scripts