How to loop Through PHP Arrays

Summary:

The foreach loop is the simplest way to loop through arrays in PHP. We believe the for loop is the more comples loop.

Three simple ways to loop through PHP arrays

Loop through PHP arrays using the top three variants of loops. The article ranks them based on their convenience. PHP foreach ranks first, followed by the for and while loop. Read more to learn about them.

Introduction

Arrays are fundamental data structures, readily available and implemented in any programming language. Arrays, unlike a variable, can keep more values, either of the same or different types. PHP has associative arrays that are much robust. PHP arrays are diverse as they can be used as dictionaries, too, storing key and value pairs.

loop through PHP arrays

Arrays are iterable, meaning that it provides a pointer that can go through the entire set of values it holds. Programming languages usually use loops to iterate over arrays, keeping the complexity of pointers abstract. So, PHP loop through array by using several variants of loops. The article ranks the top three ways to loop through PHP arrays. So, the article is a quick guide kind of an article, and if you’re looking for more comprehensive content about PHP loops, consider reading an article about loops.

Enough disclaimers, proceed, shall we?

Three ways to loop through PHP arrays

#1 – PHP foreach loop

PHP foreach loop is a convenient way to loop through arrays. It takes an array and provides two variables, one for the key, another for the value. Besides, PHP foreach does not involve any loop counters, thereby no chances of array index out of bound exceptions. Here is the syntax of this loop.

foreach($array as $value)

foreach($array as $key => $value)

  • $array – The array to loop through
  • $key    – Key value of the element
  • $value – Individual element of an array

Here’s an example of the foreach loop.

<?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 example access keys and values as it loops over an array, but that’s not a compulsion. Here’s another example of using the values only.

<?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.
 */
?>

So, this loop takes the first rank for obvious reasons. Let’s move on to the second one now.

#2 – PHP for loop

For loop PHP takes a counter variable, a boolean, and an increment statement as loop controllers. PHP loop over an array using the counter variable. Arrays values are accessible by index, as the following example shows.

<?php
$arr = ["First", "Second", "Third"];
 
echo $arr[0]; //First
echo $arr[1]; //Second
echo $arr[2]; //Third
?>

There are other ways, too but let’s not get into diversions. So, PHP for loop has syntax as follows.

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

Here’s an example of PHP loop through array using a for loop.

<?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.
 */
?>

That’s the PHP for loop. Next in line is the while loop.

#3 – PHP while loop

The while loop PHP is a bare-bones loop that only cares about a boolean statement. As long as the statement is through, it goes over and over. So, there’s a chance to run into an infinite loop with the while loop PHP. Here’s an example of this 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.
 */
?>

Voila! We have seen all three ways to loop through PHP arrays.

Conclusion – Loop through PHP arrays

The article ranks loops based on how PHP loop over array with that. PHP foreach loop is first in line, followed by the for and while loop. The article includes examples and justification for the ranking. Ultimately, the problem at hand matters, but it is always a plus to be aware of all the choices, and hopefully, this article opens up these choices for you. Learn more about PHP at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


Article Categories

Article Tags

© 2022 Confident.Systems