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
- Print the 6 times table from
6 x 1 = 6to6 x 5 = 30, one per line, with aforloop. - Write
total($prices)that adds up an array of numbers usingforeach.