Back to Blog Page
Backend Development

How to Loop Through Arrays in PHP

How to Loop Through Arrays in PHP

Written by Kolade Chris | Sep 14, 2024 | #PHP #WebDev | 4 minute Read

Whether you’re working with a simple array of items or complex multidimensional arrays, knowing how to iterate over array elements is essential for performing various tasks and displaying data in PHP applications.

In this article, we’ll explore two unique techniques for looping through arrays in PHP – for and foreach loops.

How to Loop Through An Array with the for Loop

The traditional for loop helps you do a good job looping through arrays.

The unique thing you need to do is to get the length of the array with the count() function, then echo out each element of the array by accessing each element with the iteration variable you set.

Here’s an example:

1
$myFishArr = ['Tilapia', 'Penguin', 'Catfish', 'Shark'];
2
3
for ($i = 0; $i < count($myFishArr); $i++) {
4
echo $myFishArr[$i] . "<br>";
5
}
6
7
/*
8
Output:
9
10
Tilapia
11
Penguin
12
Catfish
13
Shark
14
*/

You can take things further and access the index of each element of the array:

1
for ($i = 0; $i < count($myFishArr); $i++) {
2
$index = $i;
3
echo $myFishArr[$i] . " is at index " . $i . "<br>";
4
}
5
6
/*
7
Output:
8
9
Tilapia is at index 0
10
Penguin is at index 1
11
Catfish is at index 2
12
Shark is at index 3
13
*/

Remember any HTML in your PHP file is the template for that PHP file. This means you can do that by looping inside the HTML in that file as well.

The only things you need to do differently is to use the endfor keyword to close out the for loop and specify colon (:) after the braces of the for loop:

1
<?php
2
$myFishArr = ['Tilapia', 'Penguin', 'Catfish', 'Shark'];
3
?>
4
5
<ul class="list-group w-25 mx-5">
6
<?php for ($i = 0; $i < count($myFishArr); $i++) : ?>
7
<li class="list-group-item text-center"><?= $myFishArr[$i] ?> </li>
8
<?php endfor; ?>
9
</ul>

Here’s how that looks in the browser:

Loop thorugh php arrays with a for loop

I didn’t mean to interrupt…

Subscribe to my newsletter for coding tips, videos from reputable sources, articles from OG tech authors, and a ton of other goodies.

No BS. No fluff. Just pure software development goodies on a Sunday every week.

Thank you, let’s get back to business!

How to Loop Through An Array with the forEach Loop

The foreach loop is a cleaner way to loop through an array as you won’t deal with any length or track an iteration.

Here’s what the basic syntax of foreach looks like:

1
foreach ($variable as $value) {
2
# code to execute...
3
}

$variable is the array you’re looping through and $value is what you want each item of the array to be called.

Here’s an example:

1
foreach ($myFishArr as $fish) {
2
echo $fish . "<br>";
3
}
4
5
/*
6
Output:
7
8
Tilapia
9
Penguin
10
Catfish
11
Shark
12
*/

If you want to get the index of each value in the array, you need to map a $key to each value:

1
foreach ($myFishArr as $key => $fish) {
2
echo $fish . " is at index " . $key . "<br>";
3
}
4
5
/*
6
Output:
7
8
Tilapia is at index 0
9
Penguin is at index 1
10
Catfish is at index 2
11
Shark is at index 3
12
*/

foreach is also a convenient way to extract what you want from an array. For instance, you can extract the role of each footballer in the array below by accessing the role key with a square bracket:

1
$retiredFootballers = [
9 collapsed lines
2
['name' => 'Ronaldo De Lima', 'role' => 'striker', 'country' => 'Brazil'],
3
['name' => 'Ronaldinho', 'role' => 'Midfielder', 'country' => 'Brazil'],
4
['name' => 'Thiery Henry', 'role' => 'Striker', 'country' => 'France'],
5
['name' => 'Frank Lampard', 'role' => 'Midfielder', 'country' => 'England'],
6
['name' => 'Edwin Van der Saar', 'role' => 'Goalkeeper', 'country' => 'Netherlands'],
7
['name' => 'John Terry', 'role' => 'Defender', 'country' => 'England'],
8
['name' => 'Jay Jay Okocha', 'role' => 'Midfielder', 'country' => 'Nigeria'],
9
['name' => 'Steven Gerrard', 'role' => 'Midfielder', 'country' => 'England'],
10
['name' => 'Peter Cech', 'role' => 'Goalkeeper', 'country' => 'Czech'],
11
['name' => 'Rio Ferdinand', 'role' => 'Defender', 'country' => 'England'],
12
['name' => 'Didier Drogba', 'role' => 'Striker', 'country' => 'Ivory Coast'],
13
];
14
15
foreach ($retiredFootballers as $retiredFootballer) {
16
$role = $retiredFootballer['role'];
17
18
echo $role . "<br>";
19
}
20
21
/*
22
Output:
23
24
striker
25
Midfielder
26
Striker
27
Midfielder
28
Goalkeeper
29
Defender
30
Midfielder
31
Midfielder
32
Goalkeeper
33
Defender
34
Striker
35
*/

As you’ve seen, the $retiredFootballer array has a name, country, and role keys. That’s a chance to be creative when you want to do the looping in your HTML template:

1
<ul class="list-group mx-5" style="width: 40%;">
2
<?php foreach ($retiredFootballers as $retiredFootballer) : ?>
3
<li class="list-group-item"><?= $retiredFootballer['name']
4
. ' is a retired footballer from ' . $retiredFootballer['country'] .
5
'.' . ' He played as a ' . $retiredFootballer['role'] . '.' ?> </li>
6
<?php endforeach; ?>
7
</ul>

Loop thorugh php arrays with a foreach loop

Wrapping Up

Mastering the for and foreach loops will increase your confidence in looping through arrays of any size and complexity, making your PHP code more expressive and powerful.

Some array functions, like array_map() and array_filter(), also provide ways to extract what you want from an array and even apply a callback function, but they’re technically not loops.