Beginner Fundamentals
PHP For Loops
When you know how many times to repeat something, the for loop is a good fit. The foreach loop is made for going through arrays.
The for loop
It has three parts: start, condition, and step.
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
// Output: 1 2 3 4 5
$i = 1runs once at the start.$i <= 5is checked before each iteration.$i++runs after each iteration.
Counting down
<?php
for ($i = 3; $i >= 1; $i--) {
echo $i . " ";
}
// Output: 3 2 1
The foreach loop
foreach walks through every element of an array.
<?php
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
echo $color . " ";
}
// Output: red green blue
foreach with keys
You can also access the key of each element.
<?php
$colors = ["red", "green", "blue"];
foreach ($colors as $index => $color) {
echo "$index: $color ";
}
// Output: 0: red 1: green 2: blue