Summary - Loops
Build a multiplication table using for, while and foreach.
Summary - Loops
In this group you learned four loop types. for suits a known count, while suits condition-driven repeats, do-while runs at least once, and foreach walks array elements.
You also saw break to end a loop and continue to skip a step. Now you will combine them in a multiplication table and an element search task.
Exercise The 3 times table
Use a for loop to print the 3 times table. Let $i go from 1 to 5 and print each row as 3 x N = R. Example: 3 x 1 = 3, 3 x 2 = 6.
Show example solution
Write for ($i = 1; $i <= 5; $i++) and print echo "3 x " . $i . " = " . (3 * $i) . "\n".
Example solution:
<?php
// The 3 times table
for ($i = 1; $i <= 5; $i++) {
echo "3 x " . $i . " = " . (3 * $i) . "\n";
}
foreach and break together
To stop when you find a certain element while walking an array, use foreach and break together. foreach ($numbers as $number) walks the elements, and when you reach the target you exit with break.
For example, to stop at 4 in [1, 2, 3, 4, 5] you write if ($number == 4) { break; }; 1, 2 and 3 are printed and the loop ends.
Exercise Stop at 4
Walk through the $numbers array with foreach. Print each number with echo; but when $number is 4, exit the loop with break. So 1, 2 and 3 should be printed and the loop should stop.
Show example solution
Write foreach ($numbers as $number), first stop with if ($number == 4) { break; }, then echo $number . "\n".
Example solution:
<?php
$numbers = [1, 2, 3, 4, 5];
// Stop when 4 is found
foreach ($numbers as $number) {
if ($number == 4) {
break;
}
echo $number . "\n";
}
Test yourself
-
Which loop best fits printing numbers from 1 to 100?
- do-while
- for
- foreach
- break
Show answer
for — Correct. When the repeat count is known, for is the best fit.
-
Match each loop to its use case
- for
- Fixed number of repeats
- while
- While a condition holds
- foreach
- Walks array elements
- break
- Exits the loop