Originally published on zero2php.dev — part of the Zero to PHP course. View this lesson on the original site.
for
for is great when you need an index:
<?php
declare(strict_types=1);
for ($i = 0; $i < 3; $i++) {
echo $i, "\n";
}
foreach
foreach is the idiomatic way to walk arrays:
<?php
declare(strict_types=1);
$items = ['a' => 10, 'b' => 20];
foreach ($items as $key => $value) {
echo $key, ' => ', $value, "\n";
}
Exercise
Use for to sum 1 + 2 + 3 + 4 in a variable, then echo that sum (10).
From Zero to PHP — Control flow, functions, arrays, and the web