Foreach Loop

Last updated on

The foreach loop in PHP is perhaps one of the most helpful tools a developer is going to want when it comes to dealing with arrays or objects. If you have been writing any serious amount of code in PHP, you have quite likely used foreach many times—perhaps so many times that you've just lost count.

But let's take a second to really get into why it's so helpful: not just how it works, but why it feels like magic when you use it right.

When you are learning to code in PHP, there's this moment when you're staring at this big chunk of data and you're going, "How am I going to handle all of this without pulling my hair out? " I have been there. You are trying to balance loops, wrap your head around conditions, and just when it feels like you are about to give up, you discover foreach. It's like someone just gave you the cheat code.

Sure, there are other loops, such as for and while; however, foreach is a game changer, especially since, quite frankly, in PHP, you can almost always find yourself working with an array.

So let’s move into the section below to understand how it works.

Understanding How "foreach" Works in PHP

The PHP foreach loop works by iterating through each item in the array, executing code for each one. This is enabled through the following of some simple rules that tell it how to behave.

php foreach loop

Here's how it works: first, foreach takes the array and pulls off the first element. It takes the value of that element and assigns it to a new variable—one that you define in the loop. This variable will hold the value of each element as the loop moves through the array.

Then, the code inside the curly braces { } is executed: this can be anything you want, as perhaps you're printing the value or changing it somehow.

Once the code has executed for the first element, it moves to the next. It continues this process of setting the value of each element to the variable and executing the code inside the loop until it reaches the end of the array.

One thing to keep in mind: the variable you define in the loop is new each time through the loop. It is not directly connected to the original array, and if you do change the variable, it does not affect the array.

In this section, I will demonstrate how it is possible to use foreach inside HTML in order to loop through the data and print it on a web page.

So, what's so special about foreach?

The Basics of PHP "foreach"

The PHP foreach is used to go through every item in an array or object. But what does this really mean? Let me think for a second. Imagine that you have some sort of list of stuff, maybe a shopping cart with items, or a list of people's emails, or even something like tracking school grades, which I did something similar to in Flutter. You need to go through each item in that list and do something with it. That’s exactly what foreach is for.

The best part? The syntax is super easy:

foreach ($array as $value) {
    // do something with $value
}

You have your array ($array), and foreach element within that array, PHP automatically assigns it to $value, which you may then use inside the loop. You don't have to keep track of how many elements are inside the array, nor do you need to figure out when you've reached the end of the array. All is taken care of for you. Pretty smooth, right?

Let's take a very simple example. Imagine you have the following list of names:

$names = ['John', 'Sarah', 'Tom', 'Lisa'];

foreach ($names as $name) {
    echo $name . "<br>";
}

And there you have it! PHP iterates through the array, name by name, assigning the value to $name each time through the loop. The result? It outputs each name, one at a time. Pretty simple, but also pretty powerful.

Now, here's where things get cool: that's just the very basic way of using foreach. If you need to get creative, PHP gives you a lot of flexibility with this loop.

Anyway, let's move into the following section to learn how to iterate using foreach with both keys and values  .

Iterating with Keys and Values

Sometimes, it's not just the value that you want, but also the key that you need. PHP arrays can be associative—meaning they have keys matching to values. So, if you need to have both—and that's very often—the foreach loop has it covered.

Here is an example:

$person = ['name' => 'John', 'age' => 30, 'city' => 'New York'];

foreach ($person as $key => $value) {
    echo "$key: $value<br>";
}

Now, instead of just iterating on the values, you get both the key—'name' or 'age'—and the value—'John' or 30. See? It's that easy. That's where foreach really starts to make it shine because most of the time real-world data isn't just a simple list of names or numbers. You've got key-value pairs, and being able to handle both in one loop.

I remember working on a project where I needed to fetch some user-related data from an API. These were all enclosed within large associative arrays. If it hadn't been for foreach, the process of sorting through would have just been complete chaos. With it, though, I was able to iterate over each user's information, capturing both the key and the value of that information. Then I did anything I needed to, which could be presenting it on the screen or saving it to a database, mostly because saving an entire associative array is a bit more difficult than just saving values.

In the following section, you will understand how to modify the array during foreach loops.

Modifying the Array Inside "foreach"

Alright, let's kick it up a notch. Now, when it comes to modifying an array inside of a foreach loop, there's kind of a trick to it. I remember the first time I ever tried this—it seemed confusing at first, but once you know how it works, it's pretty straightforward.

When you use foreach, each time PHP makes a copy of every value from the array. Trying to change the value inside the loop won't update the original array. Here is an example:

You might think this will give you [2, 4, 6, 8], but nope! The original array stays the same because you're only changing the copy of each value. Original numbers don't budge.

If you want to actually change the original array, you will need to pass it by reference. Here's how:

foreach ($numbers as &$number) {
    $number *= 2;
}

print_r($numbers);

And now, when you print the array, it prints [2, 4, 6, 8]. That's because using & tells PHP, "Hey, don't just copy the value; change the actual array." This is super great when you want to change the data as you loop through it.

Anyway, let's understand how to use foreach loop with objects in PHP.

Using "foreach" with Objects

What about objects? Well, foreach flies with these, too! I have used this a million times when dealing with collections of objects in PHP. For example, say you have a set of user objects, and you want to loop through them to show their details:

Here is a simple example:

class User {
    public $name;
    public $email;

    public function __construct($name, $email) {
        $this->name = $name;
        $this->email = $email;
    }
}

$users = [
    new User('John', 'john@example.com'),
    new User('Sarah', 'sarah@example.com'),
];

foreach ($users as $user) {
    echo $user->name . " (" . $user->email . ")<br>";
}

Just like with arrays, foreach makes it very easy to loop through objects. You don't have to mess with the inner workings of the object—you just grab the properties you need and do your thing. For example, here it prints out a user's name and email.

But did you ask yourself when to use forEach in your program? Let’s break it down and see how to consider that in the following section.

When Not to Use foreach

As cool as foreach is, there are times when it's not the best option. If you need more control over the loop - like knowing exactly which item you're on (the index) - or if you need to make complicated changes to the array - a regular for might be better.

Also, remember that foreach only works with arrays and objects. If you have to iterate over anything else, like a string or a resource, you must use another kind of loop.

But for most use cases, foreach is the best. When you have an array or object and simply need to get through it with ease, look to this.

Anyway, let’s move into examples and check how we can use forEach in an HTML structure.  

PHP "foreach" Examples

Embedded PHP Foreach with HTML or JavaScript

The embedded foreach can work with HTML page in separate areas:

<?php 
  $tuts = array( "PHP", "HTML", "JavaScript" );
  foreach( $tuts as $tutorial ):
?>
<h1>CodedTag.com <?= $tutorial; ?> Tutorial</h1>
<?php endforeach; ?>

This code will print all tutorial names inside the array using the HTML heading tag with a repeated loop.

Using PHP Foreach by Reference

To use the PHP foreach by reference you have to use the & (and) operator in the extracted item. For example.

<?php
   $arr = array("item 1", "item 2");
   foreach( $arr as &$value ){
     echo $value;
   }
?>

You can also use the array directly in the foreach loop.

<?php
   foreach( $arr as &$value ){
     echo $value;
   }
?>

Foreach with Associative Array

To facilitate easy retrieval, associative arrays use names or numbers as index fields. During iteration with a foreach loop, you can extract keys and values separately. Take the following example into consideration.

<?php
   
   $assoc_array = array(  
      "name" => "Ahmed", 
      "age"  => 20,
      "job"  => "Web Developer"
   );
   
   foreach( $assoc_array as $key => $value ){
      echo $key . " : " . $value;
      echo "\n";
   }

?>

I separated the keys and values in this instance, resulting in the following output.

name : Ahmed
age : 20
job : Web Developer

During the foreach loop, each item can be accessed and the corresponding $key and $value of the array can also be accessed.

No Curly Braces with PHP Foreach

It is possible to use the PHP foreach loop without curly braces, resulting in the loop only executing the first statement and disregarding any subsequent lines.

The following example will solely display the names contained in the array based on the first statement. The second statement will be disregarded by the foreach loop.

<?php
  
  $array = array( "Ahmed", "Samy", "Montasser", "Michael" );
  foreach( $array as $arr )
    echo $arr; // execute this line only as in the loop
    echo "This line will not be executed."; // ignore this line

?>

Wrapping Up

The thing is, foreach in PHP is all about convenience. Whether you chase a long list of data, a myriad of key-value pairs, or even modify arrays, foreach does this in the most intuitive manner possible. I have done projects whereby the data seemed huge to start with; foreach has always helped me cut it down piece by piece until I got something done. Like any tool, understanding foreach is not about syntax, really; it's about knowing when to use it. It can save a lot of time and headaches as you create your apps. Think of it more than just a loop—a mindset. Once you engrain it into your style, foreach really can change the way you approach problems in PHP—making everything just a little more manageable, one step or iteration at a time.

Frequently Asked Questions (FAQs)

  • What is the basic syntax of a PHP `foreach` loop?

    foreach ($array as $value) { 
        // code to be executed 
    }
    In this structure, the loop will go through each element in the array, assigning its value to the variable $value, and then executing the code block inside the curly braces.
  • How can I iterate over both the key and value in a PHP `foreach` loop?

    foreach ($array as $key => $value) { 
        // code to be executed 
    }
    In this case, the foreach loop provides access to both the key and the value in each iteration.
  • Can I modify an array within a `foreach` loop?

    Yes, but in most cases, you'll need to pass the value by reference to modify the original array. Here's an example:
    
    foreach ($array as &$value) { 
        $value *= 2; // Modify the original array
    }
    By using & before the variable, you're telling PHP to modify the original value, not just a copy.
  • How does `foreach` handle objects in PHP?

    class User {
        public $name;
        public $email;
    
        public function __construct($name, $email) {
            $this->name = $name;
            $this->email = $email;
        }
    }
    
    $users = [new User('John', 'john@example.com'), new User('Sarah', 'sarah@example.com')];
    
    foreach ($users as $user) {
        echo $user->name . " (" . $user->email . ")";
    }
    In this example, foreach loops through an array of objects and allows you to access their properties.
  • Can I use `foreach` without curly braces?

    Yes, but it's recommended to always use braces for clarity. Here's what it looks like without them:
    foreach ($array as $value)
        echo $value; // Only this line will be executed
        echo "This line will not be executed";
    In this case, only the first statement after foreach is executed as part of the loop, which can lead to confusion.
  • What happens if I use `foreach` with an associative array?

    
    $assoc_array = ['name' => 'Ahmed', 'age' => 20, 'job' => 'Web Developer'];
    
    foreach ($assoc_array as $key => $value) {
        echo "$key: $value\n";
    }
    foreach works with associative arrays by allowing you to iterate over both the keys and the values simultaneously.
Share on: