How to use loops in PHP

Loops are a super useful control structure.

We have a few different kinds of loops in PHP: while, do while, for, foreach.

Let’s see them all!

while

while is the simplest one. It keeps iterating while the condition evaluates to true

while (true) {
  echo 'looping';
}

This would be an infinite loop, this is why we use variables and comparisons:

$counter = 0;

while ($counter < 10) {
  echo $counter;
  $counter++;
}

do while

do while is similar, but slightly different in how the first iteration is performed:

$counter = 0;

do {
  echo $counter;
  $counter++;
} while ($counter < 10);

In the do while loop first we do the first iteration, then we check the condition.

In while first we check the condition, then we do the iteration.

Do a simple test by setting $counter to 15 in the above examples, and see what happens.

You might want to choose one kind of loop, or the other, depending on your use case.

foreach

The foreach loop is used to easily iterate over an array:

$list = ['a', 'b', 'c'];

foreach ($list as $value) {
  echo $value;
}

You can also get the value of the index (or key in an associative array) in this way:

$list = ['a', 'b', 'c'];

foreach ($list as $key => $value) {
  echo $key;
}

for

The for loop is similar to while, but instead of defining the variable used in the conditional before the loop, and instead of incrementing the index variable manually, it’s all done in the first line:

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

//result: 0123456789

You can use the for loop to iterate an array in this way:

$list = ['a', 'b', 'c'];

for ($i = 0; $i < count($list); $i++) {
  echo $list[$i];
}

//result: abc

break and continue

In many cases you want the ability to stop a loop on demand.

For example you want to stop a for loop when the value of the variable in the array is 'b':

$list = ['a', 'b', 'c'];

for ($i = 0; $i < count($list); $i++) {
	if ($list[$i] == 'b') {
    break;
  }
  echo $list[$i];
}

//result: a

This makes the loop completely stop at that point, and the program execution continues at the next instruction after the loop.

If you just want to skip the current loop iteration and keep looking, use continue instead:

$list = ['a', 'b', 'c'];

for ($i = 0; $i < count($list); $i++) {
	if ($list[$i] == 'b') {
    continue;
  }
  echo $list[$i];
}

//result: ac

Download my free PHP Handbook!