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 the 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