PHP Loops
ExamplePHP
<?php
for ($i = 1; $i <= 3; $i++) {
echo "for $i\n";
}
$n = 3;
while ($n > 0) {
echo "while $n\n";
$n--;
}
$cars = ["Volvo", "BMW", "Ford"];
foreach ($cars as $car) {
echo $car, "\n";
}
foreach (["a" => 1, "b" => 2] as $key => $value) {
echo "$key=$value\n";
}Output
for 1 for 2 for 3 while 3 while 2 while 1 Volvo BMW Ford a=1 b=2
foreach is the loop you will use most in PHP: it walks through arrays and gives you the key as well when you ask for it.
Quick check
Which loop is made for walking through an array?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.