PHP – Lesson 09 : Loops Overview

In this lesson:


Loops

An overview

  • Section of code repeated over and over until a condition is met
  • Some loops work by increasing a variable by a number to count the through iterations until it reaches its max (or minimum) value preset in the loop
  • Some loops run through arrays and process each array item until it reaches the last one.

Types of Loops

There are three main types:

  • “while / do”
  • “for”
  • “foreach”

Each of these loops is explained below.


The “while” and “do…while” loops

These “two” loops are essentially the same, but with this difference: “while” loops will ONLY do something if the condition is met, but the “do” loop will do something at least once before it applies the condition. If you look at the syntax below, you will see why.

Here’s a “while” loop in plain English:

  • while (condition is met) {
    execute some code
    }

Here’s the “do…while” loop in plain English:

  • do {
    execute some code
    } while (condition to be tested);

You can see that in the “while” loop, the conditional filter is immediately applied in the first line and acts as a gatekeeper. The “do…while” loop, however, immediately says to do something right off the bat and THEN test it to see if it should keep going.

Let’s look a real example and dissect it. Let’s build a counting loop using the “while” loop.

  • $i = 1; //sets the starting counter position
    while ($i <= 100) { /*starts loop and sets condition, "as long as $i is less than or equal to 100....)*/
    echo "$i <br />"; /*print the current value of $i on the page, followed by an XHTML line break*/
    $i++; //increases the counter by 1
    } /*signals end of loop commands. Loop will restart again until $i hits the "101" mark, where it will stop.*/

The loop above will print the numbers 1-100 on a webpage, with each number on a new line.


The “for” loop

The “for” loop can do the same as above, but is less likely to result in infinite loops since all conditions are stated within the first line, as follows in plain English:

  • for (start counter; test condition; give increment) {
    code to be executed
    }

Let’s do exactly what we did in the “while” example above, but in the “for” loop format:

  • for ($i = 1; $i <= 100; $i++) {
    echo "$i <br />";
    }

The three expressions in the first line’s parentheses follow a pattern that is important for the “for” loop. What that means is that these three positions in the loop have specific purposes, as follows:

  1. This first expression sets the starting position of the count
  2. The second expression is the condition to test to know whether or not to continue running through the loop. It can be a fixed number, variable, or an expression that calculates a value.
  3. The third expression sets the interval by which to step through the loop. You generally need to step through loops 1 increment at a time, but there might be times you want to count every 10th, 13th, or other value through the loop. In that case you don’t use the standard ++ or -- but you would use += or -=. Example: starting the counter at “1” and counting every tenth number until hitting 40 would produce the following numbers: 1, 11, 21, and 31.


The “foreach” loop

Here are a couple of important distinctions:

  1. The “foreach” loop is only used with arrays.
  2. “foreach” has separate formats for associative vs. indexed arrays.

Let’s start with the Indexed array type using “foreach.” In plain English:

  • foreach (array_name as temporary_variable) {
    do something with temporary variable
    }

What this does is tell the engine to assign a temporary variable to each item in the specified array, and then do something for each item. Let’s look at a real example.

  • //define the array first
    $animals = ('dogs','cats','fish' );
    //now use the foreach loop to do something with each item in the array
    foreach ($animals as $ThisAnimal) {
    echo "$ThisAnimal <br ?>";
    }

This will print each array item on a new line in the browser, as follows:

dogs
cats
fish

Now let’s look at an associative array using the “foreach” loop. This is is a valuable combination since associative arrays provide two pieces of info about each item, as opposed to only one in indexed arrays. That means that we need a mechanism to assign temporary variables to both the key AND the value for items in the associative array using “foreach.” It looks like this in plain English:

  • foreach (array_name as key_variable => value_variable) {
    do something with key_variable and value_variable;
    }

Here it is in a real example using animals again.

  • //set the array up
    $animals = array('Dogs'=>'loyal pets','Cats'=>'independent pets','Fish'=>'boring pets' );
    //set up the foreach loop
    foreach ($animals as $pet => $description) {
    echo "$pet are $description.<br />";
    }

This would yield:

Dogs are loyal pets.
Cats are independent pets.
Fish are boring pets.


Continue

How it is used in a loop

The “continue” feature is used in a loop to tell php to skip over a specific item in the array or a specific range of items in an array.

For instance let’s use the $animal example above:

//set the array up
$animals = array('Dogs'=>'loyal pets','Cats'=>'independent pets','Fish'=>'boring pets' );
//set up the foreach loop
foreach ($animals as $pet => $description) {
echo "$pet are $description.<br />";
}

If we decide that we don’t want the “cats” variable to print to screen, we can include an “if” statement within the loop, like this:

foreach ($animals as $pet => $description) {
if ($pet == "Cats") {
continue;
}
echo "$pet are $description.<br />";
}

What this would do is test the keys to make sure they don’t hold the value of “Cats” before running through the entire loop. If, however, $pets evaluates to “Cats”, then it will hit the “continue” command, which tells PHP to bypass the rest of the arguments in the loop and skip straight to the new iteration of the loop. It would print the following to screen:

Dogs are loyal pets.
Fish are boring pets.

 


Loops Video Demos

PHP Loops Playlist

(all videos updated 9/14/15)


Control Structure : Basic Include() Demo (14:57)