Lesson 3 of 8 · 7 min

Loops

for

for ($i = 1; $i <= 3; $i++) {
    echo "Lap $i\n";
}

Three parts: start ($i = 1), keep going while ($i <= 3), and after each round ($i++ adds 1).

while

$savings = 0;
$weeks = 0;
while ($savings < 100) {
    $savings += 15;
    $weeks++;
}
echo "$weeks weeks\n";   // 7 weeks

foreach

The loop you will use most in PHP goes through every item of an array:

$fruits = ["mango", "banana", "guava"];
foreach ($fruits as $fruit) {
    echo "I like $fruit\n";
}

$prices = ["bread" => 1.5, "milk" => 1.2];
foreach ($prices as $item => $price) {
    echo "$item costs $price\n";
}

With $key => $value, you get both the key and the value.

To put an expression inside a string, join it with dots: "6 x $i = " . (6 * $i).

Your task

  1. Print the 6 times table from 6 x 1 = 6 to 6 x 5 = 30, one per line, with a for loop.
  2. Write total($prices) that adds up an array of numbers using foreach.
index.php
<?php
// 1. the 6 times table, 1 to 5


function total($prices) {
}

PHP 8.4 runs right here in your browser. The first run downloads about 12 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…