The array is a crucial data structure for storing data. They are iterable, and we could retrieve their elements one at a time in a loop. In this article, we’ll see multiple different ways to loop through an array in PHP.
Let’s begin without any further ado.
foreach: Loop through all elements in PHP Array
The foreach loop in PHP is a great way to loop through an array in PHP. I prefer it because you do not have to worry about counters and array indices. Also, It is more intuitive and readable. So, let’s see the syntax of the foreach loop.
foreach($array as $value)
- $array – The array to loop through
- $value – Individual element of an array
Let’s see the foreach loop in action.
<?php
//An array containing numbers from 1 to 10.
$numbers = [1,2,3,4,5,6,7,8,9,10];
//foreach loop to iterate over the $numbers array.
foreach($numbers as $number)
{
//A number is even if its modulo with 2 is equals to zero.
if($number%2 == 0)
{
echo $number.' is an even number.'."\n";
}
else
{
echo $number.' is an odd number.'."\n";
}
}
/*
OUTPUT
1 is an odd number.
2 is an even number.
3 is an odd number.
4 is an even number.
5 is an odd number.
6 is an even number.
7 is an odd number.
8 is an even number.
9 is an odd number.
10 is an even number.
*/
?>
See how conveniently the loop picks up each element of the array and applies the logic. There is another syntax ideal for cases where you might need an array’s key-value pairs. It is similar to the previous one but with a slight change.
foreach($array as $key => $value)
- $array – The array to loop through
- $key – Key value of the element
- $value – Individual element of an array
Don’t worry if it seems confusing because we have a code demo for this one as well.
<?php
//An array containing employee-age as key-value.
$employee_age = [
"Peter" => 22,
"Anna" => 25,
"Steve" => 30,
"Bob" => 32,
"Mark" => 35];
//foreach loop to iterate over the $employee_age array.
foreach($employee_age as $employee => $age)
{
echo $employee." is ".$age." years old."."\n";
}
/*
OUTPUT
Peter is 22 years old.
Anna is 25 years old.
Steve is 30 years old.
Bob is 32 years old.
Mark is 35 years old.
*/
?>
The foreach loop simplifies the code and makes it much more intuitive and readable. That’s the reason I like it. Some developers, however, still might prefer the conventional for a loop. So, let’s see how to loop through an array in PHP using for loop.
How to Break out of a foreach loop.
There are times when you want to loop through an array until you meet some criteria. You may be counting to a certain number or looking for a certain value. Use the break keyword whenever you need to end a foreach loop. You can also pass an integer if you need to break out of a nested foreach loop.
We have a full article on this topic if you want to see examples: How to break out of a foreach loop
for: Loop through a set number of elements in an array.
The for loop is quite a fundamental concept in many programming languages, and PHP is no different. If you’re coming from languages like C, C++, or Java, you might have been used to loop through an array using for loop. Gladly, you can do that in PHP too. Let’s see the syntax first.
for($i = 0; $i < $n; $i ++)
- $i = 0 – Initiates the counter variable $i
- $i < $n – Boolean test for counter (Loop stops if the condition is false)
- $i ++ – Increments the counter value
Let’s reuse the foreach loop’s code demo but this time use for loop instead.
<?php
//An array containing numbers from 1 to 10.
$numbers = [1,2,3,4,5,6,7,8,9,10];
//for loop to iterate over the $numbers array.
for($i = 0; $i < count($numbers); $i++)
{
//A number is even if its modulo with 2 is equals to zero.
if($numbers[$i] == 0)
{
echo $numbers[$i].' is an even number.'."\n";
}
else
{
echo $numbers[$i].' is an odd number.'."\n";
}
}
/*
OUTPUT
1 is an odd number.
2 is an even number.
3 is an odd number.
4 is an even number.
5 is an odd number.
6 is an even number.
7 is an odd number.
8 is an even number.
9 is an odd number.
10 is an even number.
*/
?>
Wonder how to redo that key-value code using for loop instead of foreach? Let’s see that as well.
<?php
//An array containing employee-age as key-value.
$employee_age = [
"Peter" => 22,
"Anna" => 25,
"Steve" => 30,
"Bob" => 32,
"Mark" => 35];
//Get the keys of the $employee_age array.
$employees = array_keys($employee_age);
//for loop to iterate over the $employee_age array.
for($i = 0; $i < count($employee_age); $i++)
{
echo $employees[$i]." is ".$employee_age[$employees[$i]]." years old."."\n";
}
/*
OUTPUT
Peter is 22 years old.
Anna is 25 years old.
Steve is 30 years old.
Bob is 32 years old.
Mark is 35 years old.
*/
?>
See, there’s a lot of hassle while doing the same code with the for loop. The code complexity increases due to the array_keys function before the loop.
We reused the code demos so that you can spot the difference and understand which option is better for you to loop through an array in PHP. Remember that readability is a huge factor in writing good code.
Now, let’s see another way to loop through an array in PHP, and that’s the while loop.
while: loop through an array based on a condition
The while loop is another renowned programming construct. It is used quite often to iterate over arrays as an alternative to the for loop. While loop checks for a condition on every iteration and break if the condition is false. To see how it works, we’ll recreate the previous code demos using a while loop.
<?php
//An array containing numbers from 1 to 10.
$numbers = [1,2,3,4,5,6,7,8,9,10];
//Initialise the loop counter
$i = 0;
//while loop to iterate over the $numbers array.
while($i < count($numbers))
{
//A number is even if its modulo with 2 is equals to zero.
if($numbers[$i] == 0)
{
echo $numbers[$i].' is an even number.'."\n";
}
else
{
echo $numbers[$i].' is an odd number.'."\n";
}
$i ++;
}
/*
OUTPUT
1 is an odd number.
2 is an even number.
3 is an odd number.
4 is an even number.
5 is an odd number.
6 is an even number.
7 is an odd number.
8 is an even number.
9 is an odd number.
10 is an even number.
*/
?>
One primary concern about the while loop is that you need to initialize the counter before the loop and also make sure to increment it in the loop. Otherwise, it will loop infinitely.
<?php
//An array containing employee-age as key-value.
$employee_age = [
"Peter" => 22,
"Anna" => 25,
"Steve" => 30,
"Bob" => 32,
"Mark" => 35];
//Get the keys of the $employee_age array.
$employees = array_keys($employee_age);
//Initialise the loop counter
$i = 0;
//while loop to iterate over the $employee_age array.
while($i < count($employee_age))
{
echo $employees[$i]." is ".$employee_age[$employees[$i]]." years old."."\n";
$i ++;
}
/*
OUTPUT
Peter is 22 years old.
Anna is 25 years old.
Steve is 30 years old.
Bob is 32 years old.
Mark is 35 years old.
*/
?>
Convenience and readability decrease even more, and now we have to be cautious about the loop counter. You can comment out the counter increment line and run the code at your end to experience an infinite loop.
Finally, we will see the do-while loop, which is an uncommon and rarely used programming construct.
When to use while vs foreach loop in PHP
You should use the while loop whenever you need to loop until a criterion equals true. Use a foreach loop whenever you need to loop through every element in an array. They can be interchangeable as you can insert a break in a foreach loop and you can add a counter to loop through every element in a while loop. We do recommend using the correct loop for your goal.
We have written a more in-depth article with examples if you want to go deeper: When to use while vs foreach loops in PHP
do-while: an alternative to the while loop
The do-while loop is rarely used because it makes the code bulkier unnecessarily. I have never used it, neither have I seen many developers using it. However, it is all about personal preferences. Let’s see an example using the same code demos, this time with the do-while loop.
<?php
//An array containing numbers from 1 to 10.
$numbers = [1,2,3,4,5,6,7,8,9,10];
//Initialise the loop counter
$i = 0;
//do-while loop to iterate over the $numbers array.
do
{
//A number is even if its modulo with 2 is equals to zero.
if($numbers[$i] == 0)
{
echo $numbers[$i].' is an even number.'."\n";
}
else
{
echo $numbers[$i].' is an odd number.'."\n";
}
$i ++;
}
while($i < count($numbers));
/*
OUTPUT
1 is an odd number.
2 is an even number.
3 is an odd number.
4 is an even number.
5 is an odd number.
6 is an even number.
7 is an odd number.
8 is an even number.
9 is an odd number.
10 is an even number.
*/
?>
<?php
//An array containing employee-age as key-value.
$employee_age = [
"Peter" => 22,
"Anna" => 25,
"Steve" => 30,
"Bob" => 32,
"Mark" => 35];
//Get the keys of the $employee_age array.
$employees = array_keys($employee_age);
//Initialise the loop counter
$i = 0;
//do-while loop to iterate over the $employee_age array.
do
{
echo $employees[$i]." is ".$employee_age[$employees[$i]]." years old."."\n";
$i ++;
}
while($i < count($employee_age));
/*
OUTPUT
Peter is 22 years old.
Anna is 25 years old.
Steve is 30 years old.
Bob is 32 years old.
Mark is 35 years old.
*/
?>
That’s it. We’ve covered pretty much all the options to loop through an array using PHP. We hope that you’ve enjoyed the article.
The difference between while and do-while loops in PHP
You may be curious if there is a significant difference between while and do-while loops? The answer is no. They accomplish the same thing and serve the same purpose. The only difference is visual and syntax. Some programmers may come from a background that utilizes do-while loops more often than regular while loops. In addition, some programmers may prefer the visual style of do-while loops.
Feel free to check out our article on the difference between while and do-while loops if you’re interested in the details of the differences.
How to loop through multidimensional arrays
You can use all of the above loops through to iterate through PHP arrays, but using foreach loops is generally the method that we recommend. If you have 1 or 2 nested arrays, the simplest approach may be to just insert loops inside another loop. You can always break out of them as needed.
On the other hand, this approach isn’t recommended when you have an unknown amount of nesting in your multidimensional arrays. A potentially smarter approach when looping through your php arrays is to use a recursive function. Using a recursive function allows you to keep your code minimal and be prepared for any amount of nesting that may come.
Learn more about looping through multidimensional arrays.
Learn More About Loops in PHP
Want to learn how to use loops in PHP? This article is part of our series on looping through PHP arrays. Check out our full series to become a PHP array loop ninja.
- Intro to PHP Array Loops
- When to use while vs foreach loop in PHP
- How to Use array_chunk with foreach loop
- How to break out of a foreach loop
- Loop Through Multidimensional Arrays
- Difference between while and do while loops
- Recursive Loop Multidimensional JSON Arrays
- Store foreach Loop Value in Array
Learn the Fundamentals of Good Web Development
Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.