News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

PHP Tutorial – 08 – Loops

There are four looping structures in PHP. These are used to execute a specific code block multiple times. Just as with the conditional if statement, the curly brackets for the loops can be left out if there is only one statement in the code block.

While loop

The while loop runs through the code block only if its condition is true, and will continue looping for as long as the condition remains true. Note that the condition is only checked at the beginning of each iteration (loop).

$i = 0;
while ($i < 10) { echo $i++; } // 0-9

Do-while loop

The do-while loop works in the same way as the while loop, except that it checks the condition after the code block. It will therefore always run through the code block at least once. Bear in mind that this loop ends with a semicolon.

$i = 0;
do { echo $i++; } while ($i < 10); // 0-9

For loop

The for loop is used to go through a code block a specific number of times. It uses three parameters. The first parameter initializes a counter and is always executed once, before the loop. The second parameter holds the condition for the loop and is checked before each iteration. The third parameter contains the increment of the counter and is executed at the end of each iteration.

for ($i = 0; $i < 10; $i++) { echo $i; } // 0-9

The for loop has several variations since either one of the parameters can be left out. For example, if the first and third parameters are left out it behaves in the same way as the while loop.

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

The first and third parameters can also be split into several statements using the comma operator (,).

for ($i = 0, $x = 9; $i < 10; $i++, $x--) { 
  echo $x; // 9-0
}

The sizeof function retrieves the number of elements in an array. Together with the for loop it can be used to iterate through a numeric array.

$a = array(1,2,3);
 
for($i = 0; $i < sizeof($a); $i++) {
  echo $i; // "123"
}

If there is no need to keep track of iterations the foreach loop provides a cleaner syntax. This loop is also necessary for traversing associative arrays.

Foreach loop

The foreach loop provides an easy way to iterate through arrays. At each iteration the next element in the array is assigned to the specified variable (the iterator) and the loop continues to execute until it has gone through the entire array.

$a = array (1,2,3);
 
foreach ($a as $v) { 
  echo $v; // "123"
}

There is an extension of the foreach loop to also obtain the key’s name or index, by adding a key variable followed by the double arrow operator (=>) before the iterator.

$a = array ('one' => 1, 'two' => 2, 'three' => 3);
 
foreach ($a as $k => $v) { 
  echo "$k => $v <br>"; 
}

Alternative syntax

As with conditional statements, the brackets in the loops can be rewritten into the alternative syntax with a colon and one of the endwhile, endfor or endforeach keywords.

while ($i < 10): echo $i++; endwhile;
 
for ($i = 0; $i < 10; $i++): echo $i; endfor;
 
foreach ($a as $v): echo $v; endforeach;

The main benefit of this is improved readability, especially for longer loops.

Break

There are two special keywords that can be used inside loops – break and continue. The break keyword ends the execution of a loop structure.

for (;;) { break; } // end for

It can be given a numeric argument which specifies how many nested looping structures to break out of.

$i = 0;
while ($i++ < 10) 
{
  for (;;) { break 2; } // end for and while
}

Continue

The continue keyword can be used within any looping statement to skip the rest of the current loop and continue at the beginning of the next iteration.

while ($i++ < 10) { continue; } // start next iteration

This keyword can accept an argument for how many enclosing loops it should skip to the end of.

$i = 0;
while ($i++ < 10) 
{
  for (;;) { continue 2; } // start next while iteration
}

In contrast to many other languages, the continue statement also applies to switches, where it behaves the same as break. Therefore, to skip an iteration from inside a switch continue 2 needs to be used.

$i = 0;
while ($i++ < 10) 
{
  switch ($i) 
  {
    case 1: continue 2; // start next while iteration
  }
}

Goto

A third jump statement introduced in PHP 5.3 is goto, which performs a jump to a specified label. A label is a name followed by a colon (:).

goto myLabel; // jump to label
myLabel:      // label declaration

The target label must be within the same script file and scope. Therefore, goto cannot be used to jump into looping structures, only out of them.

loop:
while ($finished === false)
{
  // …
  if ($try_again) goto loop; // restart loop
}

In general, the goto statement is often best avoided since it tends to make the flow of execution difficult to follow.

Recommended additional reading:
Sams - Teach Yourself PHP in 24 Hours