Loops

Looping

Sometimes we need to repeat a task over and over again.

<?php
 $friends = array("Caroline",
  "Max", "Earl", "Oleg", "Han");
 echo $friends[0] . ", ";
 echo $friends[1] . ", ";
 echo $friends[2] . ", ";
 echo $friends[3] . ", ";
 echo $friends[4];
?>

//Output Below

Caroline, Max, Earl, Oleg, Han 

Look at all these lines of code! Might a loop be more readable without repeating ourselves?

While loops

A so-called while loop runs a block of code as long as a certain condition is true.

<?php
 $number = 1;
while ($number < 4) {
  $number += 1;
  echo $number . ", ";
 }
?>

//Output Below

2, 3, 4,

Yes! This while loop increases $number by 1 as long as it's less than 4. Once at 4, the condition turns false and the loop stops.

Do while loops

A do while loop is a type of while loop that first runs the block of code then checks if the condition is true.

<?php
 $number = 1;
 do {
  $number += 1;
  echo $number;
 } while ($number > 4);
?>

//Output Below

2

See that? No matter what the condition, the loop runs at least once.

Psst: notice that the do while loop ends with a semicolon.

For loops

The for loop is a very popular type of loop. It has 3 parts: the value, the condition, and a way to change the value.

<?php 
for ($i = 0; $i < 4; $i++) {
  echo $i . ", ";
 } 
?>

//Output Below

0, 1, 2, 3, 4,

Sweet! $i starts at 0 and increases as long as the condition is true. Once it returns false, the loop stops.

Psst: $i++ is an even shorter version of $i += 1.

Foreach loop

Now, the so-called foreach loop works only on arrays, because it goes through each of their elements.

<?php 
 $heroes = array("Batman", "Robin", "Batgirl"); 
 foreach ($heroes as $hero) {
  echo $hero . ", ";
 }
?>

//Output Below

Batman, Robin, Batgirl,

Nice! In every so-called iteration, the value of an element is stored in $hero.