Beginner’s Guide to PHP – Part Five

Back in Part Four of the Beginner’s Guide to PHP, we covered the basics of arrays, and the foreach construct which is used to iterate over arrays. Today, you get to learn about for(), woot for you. According to the PHP manual, for() loops are the most complex in PHP, so I’m hoping I can break them down in a way that makes them seem nice and friendly, and without losing any important information along the way.

The Basic for Loop

The most basic of all for() loops contains three expressions: for(expression 1; expression 2; expression 3)

  • Expression 1 executes once at the beginning of the loop.
  • Expression 2 executes on every iteration of the loop (to iterate: “To say or perform again; repeat.” Answers.com); if the expression evaluates to true, the loop continues, if it evaluates to false the loop stops.
  • Expression 3 executes at the end of every iteration of the loop.

So let’s break the following down in to individual iterations:

for ($i = 1; $i < 5; $i++) {
    echo $i;
}

...this means:

Iteration 1
Expression 1 executes once, sets $i variable to 1
Expression 2 checks if $i is less than 5, is true so loop continues...
Expression 3 increments $i by 1

$i is now 2.

Iteration 2
Expression 1 does nothing, because it only executes at the very beginning of for
Expression 2 checks if $i is less than 5, is true so loop continues...
Expression 3 increments $i by 1

$i is now 3.

...and this continues until iteration reaches 5, where we have:

Expression 1 does nothing, because it only executes at the very beginning of for
Expression 2 checks if $i is less than 5, is false, so loop stops
Expression 3 isn't executed because the loop has stopped

Complicating Matters

The complex part comes in — or in my opinion, anyway — when you start skipping over expressions. The for() loop will let you remove expressions as long as you leave the semi-colons in place. For example, if $i was set further up in the script you might have just:

for ( ; $i < 5; $i++) {
    echo $i;
}

Any of the 3 expressions can be skipped, but I don't like doing this as it makes the code harder to read. I prefer having everything relevant in one place.

Oh, and Don't Forget

As if that wasn't bad enough, you can also put multiple expressions in place of one standard one, separated by commas. The PHP manual has this to say:

Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.

PHP for Tip:

The key to keeping for() speedy is to give expression 2 the least work possible. If, for example, the second expression is based on a calculation (such as counting an array), it might look like this: for($i = 1; $i < count($array); $++)

However, as mentioned above, expression 2 is executed each time the array is iterated over, which means $array is count()ed multiple times. To reduce the load (even though it may only be seconds) it's best practise to store the count in a variable and text against the variable instead. This can be done as part of expression 1 (for($i = 0, $count = count($array); $i < $count; $i++)) or before the loop:

$count = count($array);
for($i = 0; $i < $count; $i++) { ... }

That's it! Got it? :)

php beginner's guideThis article is part of the Beginner's Guide to PHP series. You can see all the guides or jump to Part Six.

10 Comments

  1. Yay! Thanks Jem~! :)

  2. all this coding jargon is turning my brain to mush. I’m just going to stick with my basic PHP includes and container layout yay.

    on the other hand please teach us about how you made them cute little bullets, they are so darn cute.

  3. Thanks, Jem. Your the best.

  4. I smell a Pants Award for Jabed’s horrible tutorial site.

    Thanks for the lesson, I hope to put this to good use.

  5. I just love the beginner’s guide, thanks Jem!

  6. Thanks Jem! You made it very understandable for us PHP newbies.

  7. “I smell a Pants Award for Jabed’s horrible tutorial site.”

    When I first stumbled across Jem’s website, I asked her for a review but she declined and recommenced me PSGR.
    So I’m not too bothered if she does give me a pants award for my ‘horrible’ tutorials because I’d like to hear some critique from her. But to be honest I don’t think my tutorials are horrible.

  8. Totally unrelated but lol. :D
    http://www.zoitz.com/archives/33

  9. Nice beginners piece – your comment about avoiding heavy computation in the loop header is spot-on, but the compiler is more intelligent than you give it credit :) (it wouldn’t count the array each loop for example, unless it was modified within the for loop itself), but the point is still totally valid, fingers crossed more beginners actual take note of it!

  10. Thanks for the tutorial. It’s made loops just that bit easier to understand for us scripting virgins!

    @esme It never ceases to amaze me how unashamedly nasty people can be under the cover of the faceless internet.