Skip to content

PHP Tutorial Loops

Looping Through Arrays

Lesson 99 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

You can go through an array in several ways. Here is a map of when to use each one.

foreach: the default

index.php
PHP
<?php
$colors = ["red", "green", "blue"];

foreach ($colors as $color) {
    echo strtoupper($color) . " ";
}
Output
OUTPUT
RED GREEN BLUE

foreach with keys

index.php
PHP
<?php
$stock = ["pens" => 40, "books" => 12];

foreach ($stock as $item => $count) {
    echo "$item: $count\n";
}
Output
OUTPUT
pens: 40
books: 12

for: when you need positions

index.php
PHP
<?php
$letters = ["a", "b", "c"];

for ($i = count($letters) - 1; $i >= 0; $i--) {
    echo $letters[$i];
}
Output
OUTPUT
cba

This walks the array backwards, which foreach cannot do directly. (array_reverse() is another option.)

Two arrays at once

When two lists line up by position, use the index.

index.php
PHP
<?php
$names = ["Ana", "Ben"];
$marks = [88, 92];

foreach ($names as $i => $name) {
    echo "$name scored {$marks[$i]}\n";
}
Output
OUTPUT
Ana scored 88
Ben scored 92

array_walk(): a callback for each item

array_walk() calls a function for each item. It can change the items when you take them by reference.

index.php
PHP
<?php
$prices = ["pen" => 10, "book" => 250];

array_walk($prices, function (&$price, $name) {
    $price = $price * 2;
});

print_r($prices);
Output
OUTPUT
Array
(
    [pen] => 20
    [book] => 500
)

Better: array_map() for a new array

If you want a new array, array_map() is cleaner than changing the old one. You will learn it in Array Mapping.

Looping and checking

index.php
PHP
<?php
$scores = [55, 91, 78];
$best = 0;

foreach ($scores as $score) {
    if ($score > $best) {
        $best = $score;
    }
}

echo "Best: $best";
Output
OUTPUT
Best: 91

(max($scores) does this in one call. Writing the loop once helps you see how it works.)

Which loop?

NeedUse
Every valueforeach ($a as $v)
Keys and valuesforeach ($a as $k => $v)
A counter or reverse orderfor
A new array from an old onearray_map()
A smaller arrayarray_filter()
lightbulb
The key can be a string
In an associative array you cannot use for with a numeric counter. foreach works for every kind of array.