Lesson 8

Repeating Program Steps

Loops let you repeat blocks of code multiple times. Depending on the type of loop, you can repeat the code a given amount of times or while a certain condition is true.

In this lesson you learn how to use the different types of loops:

  • While loops repeat the code while a given condition is true.
  • Do/While loops do the code and then repeat the code while a given condition is true.
  • For loops repeat the code a given number of times.
  • Foreach loops repeat the code separately for each element in an array or object.

You also learn how to break out of a loop or jump to the next iteration using break and continue.

Finally, you learn what array pointers are and how to manipulate them. This enables you to use loops more effectively with arrays.

While Loops

While loops execute a block of while a given condition is true. This is the syntax of a while loop:

while (condition) {
  lines of code here;
  as many as you need;
}

As with the other control structures, the while loop also has the alternative syntax that is preferred if you are mixing PHP and HTML:

while (condition) :
  lines of code here;
  as many as you need;
endwhile;

A standard use of this type of loop is to set a counter and loop through until it meets the condition. Each of the loops is called an iteration and you often find that programmers use the variable $i as the counter. The following program sets $i to 1, then loops through printing $i and adding 1 to it until $i reaches 5 and makes the ...

Get PHP and MySQL® 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.