Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

Object-Oriented Programming in WordPress: Control Structures II

by

If you've been tracking with us throughout this series, then you no doubt know that we're looking at the concepts of object-oriented programming from the beginner's perspective.

Specifically, we're looking at the topic for those who want to familiarize themselves with the paradigm, but also with how to apply the concepts within the context of WordPress; however, before we get into working with object-oriented programming and WordPress, we have to lay the foundation using the basic features that PHP provides.

Ultimately, we're working towards creating a practical example of object-oriented programming by creating a WordPress plugin. But before we do that, there are a few more things that we need to discuss.

If this is your first time reading this series, then I recommend checking out the previous articles as each article in this series builds on the one before it. If, on the other hand, you're someone who is more familiar with object-oriented programming, then you may want to revisit the series once we're getting into the practical application of the ideas.

Up to this point, we've covered the following topics.

  1. An Introduction
  2. Classes
  3. Types
  4. Control Structures: Conditional Statements

In this article, we're going to wrap up our discussion on control structures by looking at the various types of loops that PHP provides.

A Review of Control Structures

If you've read the previous article, then you recall that "control structures" refer to constructs that are provided by the language (in our case, PHP) that allow us to modify how code throughout the program based on a number of conditions.

In the last article, we looked at how we can do this through the use of conditional statements which are statements that will force the program down a path of execution based on a conditional (such as if a variable is set, if a condition is true, and so on).

Loops

But that's not the only type of control we have. In addition to conditionals, we have the ability to iterate (or loop) through sets of data so that we can take action on each item in a set of data. We can add data, remove data, display data, sort the data, and much more.

For example, let's assume that we have a set of data, perhaps a set of 10 posts, and that we want to loop through and print out the title and date of each post. Loops allow us to do this.

Whatever it is that you're looking to do, there are four types of loops that PHP provides that allow us to loop through sets of data. In this article, we're going to look a examples of each as well as some nuances of each one so that we've got yet another set of control structures that we can use when the time comes to begin writing object-oriented code.

for Loops

The for loop is often considered to be the most complicated of the loops because of the nature of how you write the code. The flow of it reads a bit unnatural.

Typically, we're used to writing code line-by-line such that each instruction is set on a single line; however, with for loops, we have a slightly different approach. First, I'll share a basic example, we'll cover the aspects of it, and then we'll look at a more detailed approach.

Here's a basic example that will count to 10 and will display each number on the screen as it does so:

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

In the first line of loop (within the parentheses after the for statement), we're doing the following:

  • initializing a variable $i and setting it equal to zero
  • setting a condition for this to continue running while $i < 10
  • incrementing $i by the value of 1 (using the post-increment operator) after each iteration

In the body of the loop, we're simply using PHP's echo function to print the current value of $i. As the loop processes the instructions, we'll see 0 - 9 printed out on the screen (since we're starting at zero and running while $i is less than 10).

Different people have different techniques for how they read code, so the strategy that I am going to recommend may not be the best for you, but when I read these types of loops, I normally read them like this:

With $i starting at zero, and while $i is less than 10, execute the body of the loop, then increment $i by 1. 

The catch is that $i can start at any value, can count up to an arbitrary amount, and can be incremented by any value. 

The more work we do with for loops, the more likely you're going to catch a few things that can optimize performance. For now, however, the basics of the for loop have been covered and the advanced techniques are a bit outside the scope of this particular article.

foreach Loops

foreach loops are similar to for loops as they iterate through a dataset, but they do so sequentially. This means there's no easy way to iterate through every, say, two items in a list (as you can with, say, $i + 2 in for loops).

This type of loop is arguably the most readable. For our example, let's assume that we have an array and the array of data contains the following names: Alpha, Bravo, Charlie, Delta, Echo, and Foxtrot. The name of the array is stored in a variable called $names.

In this case, we can setup a foreach loop to iterate through the names and display each of them on the screen like this:

$names = array( 'Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot' );
foreach ( $names as $name ) {
    echo $name;
}

Pretty easy to setup, isn't it?

Just as we shared one way to read the initial for loop in the previous section, you can read the foreach loop in the following way:

For each name in the collection of names, display it on the screen.

Or, perhaps more generally:

For each element in the collection, display it on the screen.

Anything Else?

There's one other aspect to the foreach loop that we may cover in more detail later in the series, but the main idea is that if you're familiar with associative array, that is, arrays that are indexed with a key and that have an associated value, you can setup a foreach loop to retrieve each key and value for each iteration of the loop.

For example, let's say that we have the following associative array:

$heroes = array( 'alien' => 'Superman', 'human' => 'Batman' );

When using an associative array like this, you can also setup a foreach loop like this:

foreach ( $heroes as $type => $name ) {
    echo $name . ' is a ' . $type;
}

This will result in the output reading something such as 'Superman is an alien' because 'Superman' is the value and 'alien' is his type (or his key). 

The more generic form of this loop is as follows:

foreach ( $collection as $key => value ) {
    // Work goes here
}

Nothing terribly complicated.

while Loops

With the variations of the for loops covered, it's time to turn our attention to while loops of which there are two variations (although they are called something different: while loops and do loops), but they differ only in a minor way.

But before we look at how they differ, let's take a look at the while loop, its basic format, how to use it, and how it compares with the previous for loops.

First, the basic format of a while loop is as follows:

while ( condition ) {
    // do work
}

Notice that this loop differs than our previous loops in that it accepts a conditional as part of the initial statement (hence the reason we covered conditionals in our last article).

The loop works by first checking to see if the condition is true, executing the block of code in the loop body, and then checking the condition again. This means that while loops can do any unit of work as long as the specified condition evaluates to true. 

So, sure, you can iterate through a list of numbers, run through a collection of data, but you can also do certain things while, say, a boolean value is still true. And once the flag is reaches false, then the while loop will terminate.

Let's look at an example where we're popping elements off of an array. Let's assume that the initial array has 100 elements and that we'll do this until the array has 50 elements left:

while ( 50 !== count ( $elements ) ) {
    array_pop( $elements );
}

Here, the condition will continue evaluating to true until the number of the items in the $elements array has been reduced to 50 items.

As we've done with previous loops, this is one way that you can read a while loop:

While this condition is true, execute the following code.

Of course, that's how about it looks in code anyway, isn't it?

do Loops

Finally, do loops are almost exactly like while loops except there will iterate at least one time before checking the condition.

Before taking a look at an example, here's the basic structure of the do loop:

do {
    // do work
} while ( condition );

Relatively clear, right?

So let's setup a very basic example that has us creating an array and populating it with even numbers only. To do this, we need:

  • an array to hold the numbers
  • a variable to hold what how many times we've iterated through the first 100 even numbers

With that said, one may setup the code to look like this:

$i = 1;
$even_numbers = array();

do {

    if ( 0 === ( $i % 2 ) ) {
        $even_numbers[] = $i;
    }
    
    $i++;

} while ( $i <= 100 );

And finally, as with the rest of the loops, you can read these types of loops in the following way:

Do the following block of work, then check to see if the following condition is true. If so, continue doing the work.

Anything Else?

When it comes to do loops, if you're working with a collection, you want to make sure that the collection is not empty before working on it because it will execute the code in the block of the loop before checking to see if the condition is true. This can result in errors if you try to work on a data set that is empty.

Of course, if that's what you're planning to do, then one of the other loops is better optimized for that kind of operation.

Only use do loops when you have a set of data or you're going to be executing a procedure that you know needs to execute at least once before checking on the condition that dictates the number of executions that should be performed.

What's Next?

With this covered, we've laid out everything we need to do to begin moving into a discussion of functions, attributes, scope, and other foundation aspects of object-oriented programming.

So for those of who you have felt that this series has been more or less a tour of some of the basics of PHP programming, we're going to begin moving into slightly more advanced territory in the next article.

Advertisement