Skip to content

PHP Foreach: All You Need to Know

One of the most-used functions in my life with PHP is foreach. Partly, this is because it’s just an exquisitely named function, and it maps well to how I think. Partly this is because it’s kind of the backbone of a webpage: iterate through a set of things, operating on some selectively, and then display them all.

To be good at PHP, you really must know foreach. And so that’s our goal: covering the most common and useful parts of foreach in a way that we hope makes it easy for you to understand. We’ll also cover a few of the more complex corners of this PHP language construct, but with a goal of keeping to things we write regularly or encounter in other people’s code.

Foreach vs For Loop: PHP Looping

Anyone who’s programmed much in any language has heard of a for loop. PHP improves on the for loop with the foreach loop. But before we get too deep on the foreach loop I do think there’s value in covering how these two popular things differ.

In PHP, you’ll use a for loop mostly when you want to iterate through a set of numbers. Let’s say you want a segment of code to run 20 times. You’ll probably use a for loop, like this:

for ($x = 1; $x <= 20; $x++) {
    echo "The number is: $x <br>";
}

What’s great about this code is that if you’ve seen a for loop before (with its weird three-clause syntax of “start condition”, “continue condition”, “per loop operation”), this reads quite simply. If you’ve never seen this syntax before though, it’s a lot to wrap your head around.

I’ve always found PHP foreach loops much simpler to understand. Rather than going through an abstract sequence you iterate over a pre-set thing. Here’s our for loop, made into a simple foreach.

$numbers = array( 1, 2, 3, [...], 19, 20 );
foreach ($numbers as $x) {
    echo "The number is: $x <br>";
} 

So I have a list of numbers (in PHP, we use the array language construct to contain and identify a list), and each iteration through it we’re seeing a number, which we’re showing to ourselves via an echo command.

Foreach PHP: Semantics & Code Examples

Generically, I think of the syntax of foreaching a list in PHP like this:

foreach ($from_list as $list_member) {
    // use $list_member to do things
}

Almost always, this is how a foreach in PHP will work. You’ll have a pre-existing set, most often an array, and you’ll iterate through it, doing specific things with each item.

A common operation you’ll do in PHP is filter through an array. For this, we’ll run foreach item in array like so, keeping only the odd numbers:

$keep_odds = array(); // start with an empty array of odd numbers
$numbers = array( 1, 2, 3, ..., 19, 20 );
foreach ($numbers as $x) {
    if ($x % 2 == 1) {
        $keep_odds[] = $x; 
    }
} 

Now some of this was new. One part you should maybe just trust me on: in the if I’ve used a weird syntax. It does tell us stuff is odd vs even. (It’s the PHP modulo operator, which I explained in this article about how it’s useful for more than finding odd numbers.)

The other thing to understand is the line $keep_odds[] = $x. This syntax may be new to you, and is worth understanding. What it’s doing is adding the item $x to the end of the list (or array) $keep_odds. That’s what the $array[] syntax means: “add at the end of the array the value…” This is something you’ll see a lot around PHP foreach loops, because it matches well the way we think: add something to this new set.

PHP Foreach: Get Key & Value

The next big thing you might want to do is use the keys of your PHP array. For most “list-like” purposes, you can just use PHP arrays as lists. But sometimes we’ll use PHP arrays as “key-value pairs.” When this is the case, you can just use a slightly longer way of writing out a PHP foreach loop:

foreach ($array as $key => $value) {
    # code...
}

Assuming you’ve got an array you were using as a list, the values you should expect as $key in the code above are 0, 1, 2, etc. (If you’re not familiar with it, both PHP and lots of other programming languages start counting items at 0, rather than 1. This is mostly now an annoying trivial quirk, but has its origins in very early computer performance optimizations.)

If you have an array of objects, even with custom keys, it is the as $key => $value in the foreach loop declaration that’s so important. (And just so you know, those names aren’t fixed. You can instead put into your foreach loop the names of, say $index and $object if those are how you think if your foreach key and value. Using more accurate names isn’t just possible but encouraged.)

PHP Foreach Multidimensional Array

Casually, many people will talk of “multidimensional arrays” in PHP. This name has never really clicked with me, but generally when people say it they mean that they have “an array of arrays.” To give you a more visual sense, we might have a data structure like this:

$indexed_pairs = [
    'david' => [32, 487],
    'fred' => [33, 792],
]

I’d call this a “name-indexed array of arrays.” But that’s pretty wordy. What’s important for us here is that we can iterate through this array just as normal. Foreach in PHP has no problem working with multidimensional arrays. So to iterate though our simple multidimensional array, you’ll do:

foreach ($indexed_pairs as $name => $pair) {
    echo $name.' is '.$pair[0].' years old';
}

In this case we’re using the array structure to contain more information than a simple list or set of key-value pairs. Because of that, we’re able to show both pieces of information. Like that mysterious second half of the pair. (It’s actually a random number that even I don’t know the meaning of.)

Understanding Shortcuts in a Foreach Loops

By default, a PHP foreach loop will dumbly move through all the items of your array (or other Iterator implementing object, but we’ll skip further discussion of that for now). So if you’ve got two items in your array, as we do above, you’ll just see both items go through the array. But in cases where you have hundreds or thousands of items in your array, it’s quite common that you want to do something other than run through them all. After all, your site’s visitors are busy.

In those cases, it’s important to know that there are some pretty simple optimizations you can make in your PHP foreach loops to make your whole function or script move faster. They are break and continue. I sometimes get both of them confused about using them in PHP foreach loops to this day, so let’s continue to break them down. (See what I did there? 🤪)

What is a PHP continue in a Foreach Loop

The first way you may improve a foreach loop in PHP is by using the continue keyword. What it’ll do for you is skip past the rest of the lines of the PHP code within your foreach loop. Let’s say that you have a pretty complex operation in your loop, like 20 lines of code. If you have a “guard clause” at the start that says, “if the value is under 500, skip the rest of this code” you’ll get some performance gains. Those other 20 lines won’t execute.

To show that continue in PHP code:

foreach ($indexed_pairs as $name => $pair) {
    if ($pair[1] < 500) {
        continue;
    }

    echo $name.' is '.$pair[0].' years old';
}

What this does is it “continues the foreaching.” We’ll only see the echo line happen for $pairs where the second element ($pair[1]) is 500 or more.

That’s what’s always confused me about continue in a PHP foreach. You do not read “continue” as “keep executing the code inside of the loop.” Instead, a continue in a PHP foreach means instead “continue on to the next item of the foreach iteration.” Remembering that is crucial for being able to think clearly about foreach code.

What is a PHP foreach break statement doing?

Break is quite different from continue. Both change the flow of operations in a PHP foreach loop, but break stops the execution of the entire foreach, where continue just stops the execution of the specific work item being iterated though.

Again, let’s look at code:

foreach ($indexed_pairs as $name => $pair) {
    if ($pair[1] < 500) {
        break;
    }

    echo $name.' is '.$pair[0].' years old';
}

What this does is quite different: it means that if the value of $pair[1] (the second item in the array which is the “value” in the multidimensional array) is ever below 500, no more items in the $indexed_pairs array will even be iterated through. That is, the foreach will have stopped before it processes them. They just never happen.

Again, I think it’s worth emphasizing and rephrasing. In a PHP foreach, you say break because you want to completely stop all execution of anything in the foreach. You’re thoroughly “breaking” it, rendering it completely inoperable for the rest of the executions that would otherwise occur in the iteration. It’s a small clarification, but an important one.

Why Foreach is Great for PHP

So let’s break it off there, PHP’s foreach construct is one of my favorite corners of the language. And I hope you now have a much clearer sense than before of what it does (and doesn’t) do for us. It’s a great way that we can sort through data structures (anything from a list to a multidimensional array) and do whatever we want with it.

And if we want to increase efficiency, we can make our foreach’s continue through their process faster. And if we’re really done, we can break those foreach loops entirely.

I wish you good luck. For each learner of PHP, loving foreach is an important development stage. Cheers!

Yay! 🎉 You made it to the end of the article!
David Hayes
Share:

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Joshua Otwell
July 30, 2020 10:42 am

Awesome post and very informative. I learned a great deal from reading it. Thanks for sharing.

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!