PHP Pandas: Loops

← Back to Index

Iterators are useful when you have a collection of values. Sometimes, the word 'loop' is a better way to describe an iterator. We'll use these techniques to allow a piece of code to run repeatedly until (or while) a condition is met.

Some loops are like saying "Knock on a door until someone answers.", and others are more similar to "Count every body buried in my basement.". Let's take a closer look at how these structures might be implemented in PHP.

While

The while loop will continue to run a snippet of code while the provided condition is true. Let's construct an example using a counter.

<?php

// Set the panda counter to zero.
$pandas = 0;

// Iterate while $pandas less than 50.
while ($pandas < 50) {

    // Output the number of panda butlers.
    echo "We have {$pandas} panda butlers!\n";

    // Increment the counter.
    $pandas++;
}

First, we'll set a counter called $pandas to zero. Now we can begin creating our first loop. Hurray! We need to begin our while loop with the word while followed by a condition within the ( rounded ) brackets, and finally a block of code held within { curly } braces.

The while loop takes a similar form to the if statement. The difference is that the code within the { block } portion will continue to execute, over and over again, while the condition is equal to true.

Let's execute the code and see what happens, I'm excited to meet the pandas.

We have 0 panda butlers!
We have 1 panda butlers!
We have 2 panda butlers!
We have 3 panda butlers!
We have 4 panda butlers!
We have 5 panda butlers!
... lots more! ...
We have 41 panda butlers!
We have 42 panda butlers!
We have 43 panda butlers!
We have 44 panda butlers!
We have 45 panda butlers!
We have 46 panda butlers!
We have 47 panda butlers!
We have 48 panda butlers!
We have 49 panda butlers!

Woah! That's a lot of pandas. The loop begins and checks that the value of $pandas is less than 50. It is less than 50, in fact, it's set to 0, so the code within the block portion of the loop is executed. This means that the count of pandas is echoed out, and the $pandas counter is incremented.

The loop begins once again, this time with a $panda value of one. It's still less than 50, so the block is executed again. This process happens over and over again, until the 51st iteration of the loop, when the value of $pandas is finally greater than 50. The condition is now evaluated as false, the block isn't executed this time, and our code continues to the next line after the while loop.

While loops are a fantastic way of waiting for something. Let's try a more applicable solution that will demonstrate this loop in action.

<?php

// Create an empty database connection.
$database = null;

// Iterate while the database isn't set.
while ($database == null) {

    // Attempt to connect to the database.
    $database = createDatabaseConnection();

}

For now, ignore the createDatabaseConnection(), we haven't taken a look at functions yet. Just go ahead and assume that it will attempt to set the $database variable to an instance of a database connection.

We begin with a $database variable set to null, and since the loop checks that the value is null it will certainly be executed once. The loop block will attempt to create a new database connection. If it does, then the code will continue. If the creation of the database connection fails, then the $database variable will still equal null, and the loop will execute once more.

This means that the code will continue to loop until we have a database connection. We could put our database code after the loop, and feel confident that we will have an active database connection when PHP gets to that part of our application.

Do While

The do while loop is very similar to the while loop, except for one minor difference. Let's take a look at a syntax example. Why don't you try to spot the difference?

<?php

// Set the panda counter to zero.
$pandas = 0;

// Iterate...
do {

    // Output the number of panda butlers.
    echo "We have {$pandas} panda butlers!\n";

    // Increment the counter.
    $pandas++;

// ... while $pandas less than 50.
} while ($pandas < 50);

Well, did you work it out? First let's take a look at the syntax. We begin with a do keyword. Unlike the while loop, next we have the block section of our loop container within curly braces. Next, we have the while keyword, followed by our condition.

The condition works in an identical way to the while loop. The only difference between these two loops is that the do while loop will always execute the code block at least once. It will execute the block before it checks the condition for the first time.

For

It's time to take a look at a for loop. This one will be a little tricky to explain, so we had best lead with an example.

<?php

// Iterate for 50 repetitions.
for ($i = 0; $i < 50; $i++) {

    // Output the number of panda butlers.
    echo "We have {$i} panda butlers!\n";
}

In the above example we've recreated a similar loop to our original while loop, except that we don't need to manage the counter variable ourselves.

We're more than familiar with the code block held between the curly braces, so let's take a close look at the first line.

<?php

for ($i = 0; $i < 50; $i++)

Of course, our for loop begins with a for keyword. Next, we have a set of ( rounded ) brackets. These are normally used to hold a strict condition, but the for loop is a little different. Within the brackets we find three short statements.

The first statement is used to set the counter for our loop to its initial value.

<?php

$i = 0;

In this instance we're setting a variable named $i to zero. Normally, I'd encourage you to use descriptive names for your variables, but $i is somewhat of a tradition. In fact, most of the variables used during the construction of a for loop are single letters, and $i appears to be the most common of all. I'm honestly not sure why this is, but it's a tradition that has been taught throughout the ages. If anyone reading happens to know where this tradition came from, then please do let me know! I'll update the book. My best guess would be that $i stands for iteration counter!

Next, we have our condition.

<?php

$i < 50;

This is the part of the loop we are familiar with from the previous sections. We're telling PHP to continue to execute our code block while the value of $i is less than fifty.

Finally, we have a statement to adjust our value.

<?php

$i++;

We can use this to increment our counter variable. This statement will be executed with each iteration of our loop. This means that the first line of our for loop could be expressed as the following format.

<?php

for (_BEFORE_; _CONDITION_; _AFTER_EACH_)

The first section is executed before our loop is executed. The second statement, or the condition, is evaluated every time the loop is executed. Finally, the third statement is executed after each loop iteration.

As you can see from the fewer amount of lines in the example, a for loop is a great way of implementing a loop when some form of counter is involved.

Don't forget! You're not limited to purely incrementing counters. You could increase the counter by a greater amount for a larger step, or even multiply it!

Foreach

Foreach loops are useful when used in combination with iterable types such as arrays. The number of iterations of this loop is determined by the number of items within our array. Let's take a look at an example.

<?php

// Create an array of pandas.
$pandas = ['Lushui', 'Pali', 'Jasmina'];

// Iterate our panda array.
foreach ($pandas as $panda) {
    echo "Hello there {$panda}!\n";
}

We've created a small array of pandas. We're masters of arrays already, aren't we? This is no problem for us at all. Let's focus on the next line instead.

<?php

foreach ($pandas as $panda)

The foreach loop starts with a foreach keyword. Sorry, spoiler alert! Am I right? Next we have a set of ( rounded ) brackets. Within the brackets we have two variables separated by the keyword as. We're telling PHP to loop through all of the elements in the array, and for each iteration set $panda to the current array element.

The final part of the loop is of course the code block within curly brackets. We're more than familiar with these code blocks by now. They contain the code that is executed with each iteration of the loop.

For the first iteration of our loop $panda will be set to 'Lushui', for the next iteration $panda will be set to 'Pali', and for the final iteration $panda will be set to 'Jasmina'.

This is my most used loop. I'd say I use it roughly 23,543 times a day. Something like that! It's because I enjoy working with arrays.

In a previous chapter, we discovered how to provide our own keys for arrays. You might want access to the array key, as well as its value within your for loop. Well don't worry buddy! PHP can do that for you. Let's take a look at the syntax.

<?php

// Create an array of pandas.
$pandas = [
    'first'     => 'Lushui',
    'second'    => 'Pali',
    'third'     => 'Jasmina'
];

// Iterate our panda array.
foreach ($pandas as $position => $panda) {
    echo "You're the {$position} panda, {$panda}!\n";
}

This time, we have an array with custom keys. We're using strings for both keys and values, but they could be anything. Instead of simply assigning a new variable for each loop iteration, we provide a temporary key and value placeholder separated by a => symbol.

Let's take a look at the values of both variables with each loop iteration.

  • First Iteration ($position = 'first') ($panda = 'Lushui')
  • Second Iteration ($position = 'second') ($panda = 'Pali')
  • Third Iteration ($position = 'third') ($panda = 'Jasmina')

We can use these temporary variables to accomplish any of our sick little master plans. They are completely at our disposal.

It's worth noting that a copy of your array elements are passed into the foreach loop block. This means that any changes to the variable within the loop, will not be reflected once the loop has completed.

T> If you'd like to change the value of the element during the foreach loop, simply use the key => value format, and access the property by key through the original array. For example $pandas[$position] = 'Foo!;.

This was the final loop that I have to share in this chapter, but before we call it quits, let's take a look at some of the control keywords available to us for use within our loops.

Control

In the forks chapter, we discovered how to use break to exit out of a fork and continue with the execution of our code. We can also use break inside a loop to exit out and continue processing our application. It's a handy statement like that. Here's a quick example.

<?php

// Create an array of pandas.
$pandas = [
    'first'     => 'Lushui',
    'second'    => 'Pali',
    'third'     => 'Jasmina'
];

// Iterate our panda array.
foreach ($pandas as $position => $panda) {
    echo "You're the {$position} panda, {$panda}!\n";
    break;
}

This loop will only output for the first iteration of the loop. As soon as PHP reaches the break statement, it will exit the loop and continue processing the application.

The next control statement is continue. Using continue in the code block will instruct PHP to complete the current iteration at that point, and continue to the next iteration. It's useful for 'skipping' loop iterations.

Let's take a look at an example. Why don't we throw an if statement into the mix? We're a master of those now, aren't we?

<?php

// Create an array of pandas.
$pandas = [
    'first'     => 'Lushui',
    'second'    => 'Pali',
    'third'     => 'Jasmina'
];

// Iterate our panda array.
foreach ($pandas as $position => $panda) {

    // If the position variable equals 'second'.
    if ($position == 'second') {

        // Break the iteration.
        continue;
    }

    // Output.
    echo "You are the {$position} panda, {$panda}!\n";
}

Take a look inside the loop block. We have an if statement that will continue to the next iteration if the $position temporary array key variable is equal to the string 'second'. Let's take a look at the result, shall we?

You are the first panda, Lushui!
You are the third panda, Jasmina!

As you can see, the second iteration of the loop hit the continue keyword, skipping the echo statement and continuing to the third iteration.

In the next chapter, we're going to be taking a look at functions. They'll help to give our code some structure.

My books are available online for free to encourage learning. However, if you'd like for me to keep writing, then please consider buying a digital copy over at Leanpub.com.

It's available in PDF, ePub, and Kindle format, and contains a bunch of extras that you won't find on the site. I have a full-time job, and I write my books in my spare time. Please consider buying a copy so that I can continue to write new books from the comfort of my sofa!