php 101

Loops

A core feature of any programming language is its ability to iterate, or "loop" through a series of values, performing an operation or testing a condition on each value. There are several ways to loop through values in PHP. A common one is the "foreach" loop, which says "For every value in the following array, do something." It looks like this:

In practice, you'll probably want to do something like iterate over the test scores in our $scores array and print out each one. Let's try that.

In this example, foreach() simply goes through every element in the $scores set and temporarily sets it to $score. It then outputs $score to the screen. Instead of spitting out raw scores, we could easily have put our test from the previous section in between the curly braces, and output something different depending on whether the student passed.

But what about the student names? When looping through an associative array this way, PHP just gives us the values. If you want the student names as well, you'll have to ask PHP to give you both the "keys" and the values. That's done like this:

We use the $name => $score (often referred to as $key => $value) syntax to get at both the lookup name and its value.

Another common loop is used to iterate through a certain number of things. For example, a loop that counts to 34 would look like this:

The meat of the action is on line 3, where you'll find three sections separated by semicolons. The first initializes a counter at 1. The second tests to see whether the value of $counter is less than some number - in this case 34. The third increments the counter up by one (the syntax += 1 means "take the old value of $counter and add one to it.")

I promised earlier to show you a better way to average any number of numbers without hard-coding the variables or the divisor. Now we have the skills to do that! Let's return to our indexed array of scores, iterate through it, counting up by one each time through the loop, and doing the final math at the end. Afterwards, I'll show you an even cooler way to do it, without the looping counter.

Cool, huh? There's nothing new in this script whatsoever - you're just putting together things you've already learned. PHP, like so many things, follows the 80/20 rule - you'll use 20% of the features 80% of the time. So how could you write a similar script without a counter? Easy - just count the number of elements in the array instead of incrementing a counter on each pass through the loop:

The built-in count() function does exactly what its name implies - it returns a count of the number of elements in an array.

There's one more type of loop you'll see a lot of -- the "while" loop. Use this type of loop when you want to keep on doing something until a set is exhausted, or as long as some condition remains true. For example. let's say your script should pull the most recent four stories out of a database and you want to render each story to the page until you hit story #5, then stop. We'll use our $scores array here rather than database output, but you get the idea:

When you run the script, notice that it prints only the first four elements of the array, then stops.

The other interesting thing we're doing here is on line 6. Remember how we access the values of an indexed array with something like $scores[3] to get at the 4th element? But in this script, we've written $scores[$counter]. Each time through the loop, $counter is incremented. Since $counter was initialized as zero, the first time through the loop we get the value of $scores[0], the second time through we get $scores[1], and so on.