PHP For Loops
for has three parts — init, condition, step — separated by semicolons. Use it when you know how many times you'll loop.
The shape
PHP
for ($i = 0; $i < 5; $i++) {
echo $i, PHP_EOL;
}
Backwards
PHP
for ($i = 10; $i >= 0; $i--) {
echo $i, ' ';
}
Multi-variable for
PHP
for ($i = 0, $j = 10; $i < $j; $i++, $j--) {
echo "$i $j", PHP_EOL;
}
Iterating an array
You can do this with for, but foreach is shorter and safer:
PHP
// Old style
for ($i = 0, $n = count($items); $i < $n; $i++) {
echo $items[$i];
}
// Modern
foreach ($items as $item) {
echo $item;
}
Template syntax
PHP
<?php for ($i = 1; $i <= 10; $i++): ?>
<li>Row <?= $i ?></li>
<?php endfor; ?>
Tip: Cache
count($items) in the init clause. Otherwise PHP re-evaluates it on every iteration — fine for small arrays, wasteful for big ones.Example
Exercise
Cache count once in the init clause.
for ($i = 0, $n =
($items); $i < $n; $i++) {}
Five letters.
Discussion
Loading…