PHP while loops

This Might take a While

If you’ve never been introduced to the concept of a loop, think about it this way. Let’s say that you’re looking at an excel sheet. In that excel sheet you have rows that go down the sheet. Each row has some data inside of it. To read the contents of the next row, you move down. You can keep reading the contents of each row up until you reach the last row of that excel sheet.

With a loop, you can read the information from a particular row, add 1 to the current row number, and move to the next row. You can then read the contents of the next row.

Instead of looking at an actual excel sheet, we’ll look at an array. The array can be used to model rows and columns of something like an excel sheet.

<?php

$best_cars_ever_made = [
    "S13 240sx",
    "Datsun 240z",
    "Mazda RX7",
    "MKIV Supra",
    "R32 GTR",
    "R34 GTR",
    "C5 Corvette",
    "C6 Corvette",
    "C8 Corvette",
    "Porsche 911",
    "Subaru STi"
];

// Prints an individual statement
// Displays Datsun 240z
echo $best_cars_ever_made[1];

?>

We have the following array: $best_cars_ever_made. We’ve already looked at how to display an individual element from the array, but how can we keep displaying element after element, starting at “S13 240sx” and ending at “Subaru STi?”

We can do that with a loop. There are numerous loops that we’ll cover, but we’re going to be focusing on only one here: the while loop.

while ( expression is true ) {
  do something
}

PHP while loops say, “while the expression is true, do something inside of the loop body.” If we passed the value “true” to the conditional expression, the loop would run forever (well, as long as PHP allows it to run before it crashes). Programming languages like Java do allow you to run the loop forever and it’s actually pretty common to see a while(true) loop; in PHP, the always true loop will run until it times out; at that point an error is returned.

The big takeaway: make sure that your while loop ends eventually.

What kind of expression are we testing? You’ve already done this type of testing with if statements. It’s just a conditional. So you can say something like:

  1. while ( $x < 10 )
  2. while ( $name != “Dino” )
  3. while ( $brand == “Ferrari” || $brand == “Porsche” )

Inside of the loop body, you have your statements that execute. You also need to have a way to break the conditional expression. For example, if you are testing while( $x < 10 ), the value of $x will eventually have to change to a value that’s greater than or equal to 10 in order for the loop to stop executing.

Let’s look at an example and walk through it.

<?php
$x = 0;
while( $x < 2 ) {
  echo $x;
  $x++;
}
?>

In the example above:

  1. PHP assigns the integer value 0 to $x.
  2. It encounters the while statement.
  3. PHP tests the conditional. Is the value at $x less than 2? The value that’s currently stored inside of $x is 0. So, is 0 less than 2? Yes. So, move into the loop body.
  4. PHP encounters the echo statement and prints out the value of $x, which is 0.
  5. The variable $x is incremented from 0 to 1 with the post-increment operator (++).
  6. PHP returns to the top of the while loop and tests the condition again. Is $x less than 2? Remember, the value of $x was incremented inside of the while loop body. The variable $x now contains the value 1. So, is 1 less than 2? Yes. Move into the loop body.
  7. Echo the value of $x, which is now 1.
  8. Increment $x. The integer value 2 is now stored inside of $x.
  9. PHP returns to the top of the while loop and tests the condition again. Is $x less than 2? The value of $x was incremented inside of the loop body and now stores the value 2. So, is 2 less than 2? No. Skip the loop body and continue execution after the loop’s closing curly brace.
  10. The result that’s displayed on the screen is: 01

We can now apply the same logic to our $best_cars_ever_made array.

<?php

$best_cars_ever_made = [
    "S13 240sx",
    "Datsun 240z",
    "Mazda RX7",
    "MKIV Supra",
    "R32 GTR",
    "R34 GTR",
    "C5 Corvette",
    "C6 Corvette",
    "C8 Corvette",
    "Porsche 911",
    "Subaru STi"
];

$i = 0;

while ( $i < 11 ) {
    echo $best_cars_ever_made[$i] . "<br>";
    $i++;
}

?>

We begin by counting the number of elements in the array. There are 11 total elements inside of the $best_cars_ever_made array. We can use that information inside of the loop test. We also know how to print out an individual element from an array: echo $best_cars_ever_made[5]. To print the first array, we need to print the value at index 0. To print the last value, we need to print the value at index 10.

So, we initialize a counter variable $i to 0; it’s also going to be used as the array index variable. To print out each array element, we’ll start at 0 and work our way up to 10 since the last element inside of the array is at index 10. We know that we have 11 elements so our condition can be either while($i < 11) or while($i ≤ 10). If we start at 0, we’re going to end at 10 either way.

Inside of the loop body, we pass the value of $i to the $best_cars_ever_made array and echo out the element that’s returned. Right after that, the variable $i is incremented and the processes is repeated.

If we walk through the example:

  1. PHP sets $i = 0.
  2. PHP tests to see whether $i is less than 11.
  3. Since $i is less than 11, PHP enters the loop body.
  4. PHP evaluates the expression $best_cars_ever_made[$i]. The variable $i is replaced with 0.
  5. PHP grabs the element returned by $best_cars_ever_made[0], which in this case is “S13 240sx,” and echoes it out.
  6. The variable $i is incremented to 1 and the process repeats.
  7. This keeps repeating until $i is set to 11. On the 11th attempt, the condition breaks.
  8. The output will be each vehicle listed one right underneath the other due to the <br> tag.

If you’re dynamically generating arrays, most of the times the total number of elements in the array is unknown. PHP has a helper function that can aid us with that: count(). The count() function accepts an argument, which is the array, and returns the total number of elements inside of it. In this case, count($best_cars_ever_made) will return 11. We can substitute the count() function for 11 and our while loop conditional statement will be dynamic.

<?php

$i = 0;

while ( $i < count($best_cars_ever_made) ) {
    echo $best_cars_ever_made[$i] . "<br>";
    $i++;
}

?>

We can simplify the above code even further by moving $i++ inside of the square brackets of the $best_cars_ever_made array. Remember that PHP evaluates the variable first and then increments it after it has been evaluated.

<?php

$i = 0;

while ( $i < count($best_cars_ever_made) ) {
    echo $best_cars_ever_made[$i++] . "<br>";
}

?>

One final thing to note is that if the condition is never true, PHP just skips over the while loop. So, if $i was initialized to 20 for the example above, PHP would test to see whether $i was less than 11. Since 20 is not less than 11, PHP would just skip over the loop.

PHP Tutorial Series

Continue your learning with these articles

PHP Switch Statements

Why Not “Switch” from If/Else?

PHP – P28: Switch Statement

Are you tired of writing if/elseif/elseif/…/else statements? You’re not alone. There is a more elegant way to write such large statements: the switch statement.

PHP while loops

This Might take a While

PHP – P29: WHILE LOOPS

The while loop says, “while the expression is true, do something inside of the loop body.” If we passed the value “true” to the conditional expression, the loop would run forever (well, as long as PHP allows it to run before it crashes).

PHP Do While Loops

WHAT DO YOU DO WHILE DOING DO-WHILE LOOPS?

PHP – P30: DO WHILE LOOP

A regular while loop will skip over the loop body if the expression that’s evaluated is never true. But what if we need the contents of the body to be executed at least once? That’s what the do-while loop does for us.

Leave a Reply