You can go through an array in several ways. Here is a map of when to use each one.
foreach: the default
<?php
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
echo strtoupper($color) . " ";
}
RED GREEN BLUE
foreach with keys
<?php
$stock = ["pens" => 40, "books" => 12];
foreach ($stock as $item => $count) {
echo "$item: $count\n";
}
pens: 40
books: 12
for: when you need positions
<?php
$letters = ["a", "b", "c"];
for ($i = count($letters) - 1; $i >= 0; $i--) {
echo $letters[$i];
}
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.
<?php
$names = ["Ana", "Ben"];
$marks = [88, 92];
foreach ($names as $i => $name) {
echo "$name scored {$marks[$i]}\n";
}
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.
<?php
$prices = ["pen" => 10, "book" => 250];
array_walk($prices, function (&$price, $name) {
$price = $price * 2;
});
print_r($prices);
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
<?php
$scores = [55, 91, 78];
$best = 0;
foreach ($scores as $score) {
if ($score > $best) {
$best = $score;
}
}
echo "Best: $best";
Best: 91
(max($scores) does this in one call. Writing the loop once helps you see how it works.)
Which loop?
| Need | Use |
|---|---|
| Every value | foreach ($a as $v) |
| Keys and values | foreach ($a as $k => $v) |
| A counter or reverse order | for |
| A new array from an old one | array_map() |
| A smaller array | array_filter() |
The key can be a string
for with a numeric counter. foreach works for every kind of array.