5 Ways To Loop Through An Array In PHP

PHP, just like most other programming languages has multiple ways to loop through arrays. The most popular ways to do it usually is with a while, for and foreach operator, but, believe it or not, there are more ways to do it with PHP. In this article I will walk-through each possibility for reading arrays whilst looping.

1. While Loop

The while loop is probably the most popular because of it’s recognizable and meaningful name. I always like to think of the while loop as the following.

Whilst something is true, the loop will continue looping or vice versa.

This method is commonly used when working with database results in the style of arrays but at the same time, are a completely feasible way to read non-database result-arrays.

With a plain array, we can create a true or false value depending on if the array has been looped over till the end. To achieve this, another variable must be created, an index indicator variable that does two things, allows us to pick out each of the values in the array as-well as instructing the while loop when to stop. It’s somewhat very similar to how a for loop works, which we will touch on later.

PHP Code

        $CodeWallTutorialArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread", "RedSauce"];
        $arrayLength = count($CodeWallTutorialArray);
        
        $i = 0;
        while ($i < $arrayLength)
        {
            echo $CodeWallTutorialArray[$i] ."<br />";
            $i++;
        }

Output

Eggs
Bacon
HashBrowns
Beans
Bread
RedSauce

2. For Loop

As demonstrated in the last section for while loops, you will see how similar the for loop is. It uses the very same concept for looping and picking out information from the array. Three parameters are needed for the for loop and they are as follows –

  1. An initial counter set to a certain value, usually zero.
  2. A Boolean test, usually involving the initial counter.
  3. A counter increment eg: counter++.

The start of the loop will always look similar to the following –

for ($i = 0; $i < count($arr); $i++)

What’s really important to note here is that you must use semi-colons after the first two parameters otherwise the code will throw an exception. Also, there is no need to increment the counter within the loop, as the for operator does this for you. Let’s put this loop into action in the following PHP.

PHP Code

        $CodeWallTutorialArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread", "RedSauce"];

        for ($i = 0; $i < count($CodeWallTutorialArray); $i++)  {
            echo $CodeWallTutorialArray[$i] ."<br />";
        }

Output

Eggs
Bacon
HashBrowns
Beans
Bread
RedSauce

3. Foreach Loop

This type of loop is my personal favorite way to read arrays, there is no need for a boolean test, just simply pass in the array and do what you want with it. It’s both easy to use, understand and comes in handy for many use-cases. There isn’t a mandatory rule to use a numeric index to pick out data values, the foreach loop essentially rids this concept for you. Let’s see it in action –

PHP Code

       $foodArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread"];

        foreach ($foodArray as $food)  {
            echo $food ."<br />";
        }

Output

Eggs
Bacon
HashBrowns
Beans
Bread

As you can see within the code example, there is much less fluff in terms of code. And, if you name your variables well, the code will make a lot more sense than other looping methods.

4. Do While Loop

You could almost say the do while loop is pretty scarce among PHP code, I personally rarely use it and similarly rarely see it from other peoples code neither. It’s essentially a longer or code-bulkier way of executing a while loop, which in a way, is pretty pointless. At the same time, it’s arguably more readable, but ultimately, it all comes down to preference.

With the do while loop, you will need to create a test within the while operator, just as you would in a pure while loop case.

PHP Code

       $foodArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread"];
        $i = 0;
        
        do {
            echo $foodArray[$i] . "<br />";
            $i++;
        }
        while ($i < count($foodArray));

Output

Eggs
Bacon
HashBrowns
Beans
Bread

As you can see in the code, there is a need to create an increment index value that will work part as the test and part to access values from the array.

5. Array Iterator

Now, this is a slightly more advanced method of looping over arrays is called an ArrayIterator. It’s part of a wider class that exposes many accessible variables and functions. You are more likely to see this as part of PHP classes and heavily object oriented projects. Again with this functionality, you may find it more preferable to others or vice versa. The documentation on this class is well worth eye-balling as you can see exactly what benefits it offers. For example, it instantly exposes a count of the array which is quick and useful.

PHP Code

        $programmingLanguagesArray = ["PHP", "C++", "C#", "Python", "Java"];
        
        $arrObject = new ArrayObject($programmingLanguagesArray);
        $arrayIterator = $arrObject->getIterator();

        while( $arrayIterator->valid() )
        {
            echo $arrayIterator->current() . "<br />";
            $arrayIterator->next();
        }

Output

PHP
C++
C#
Python
Java

Function References

Here are the links to the documentation on each of the loops used within this article. Check them out as they are extremely informative and useful for bookmarking for reference later.

Summary

Interesting Links

With the demonstration of five ways to loop over arrays, you have the luxury of picking a preferred and truly personal way of doing things yourself. In some cases, one will perform better than the other with regards to what you need to achieve. I hope this comes in useful, now go do some cool stuff with some loops! Finally, feel free to copy and of the code in this article to use in your own projects or merely reference.

5 Ways To Loop Through An Array In PHP
Posted in PHP

You May Also Like

One thought on “5 Ways To Loop Through An Array In PHP

  1. That’s a nice article to link to as some sort of cheatsheet, thanks!

    I think you’ve missed out on the array functions though, even if most of them are meant to create new arrays like `array_map` or `array_filter` you can also use `array_walk` to loop through an array, I use for consistency on my projects that lack some kind of Collection class since it uses a similar callback pattern as the other array functions.

Leave a Reply

Your email address will not be published.