These examples combine loops with conditions and arrays. Read the code, run it and change it.
FizzBuzz
Print 1 to 15. For multiples of 3 print Fizz, for 5 print Buzz, and for both print FizzBuzz.
<?php
for ($i = 1; $i <= 15; $i++) {
if ($i % 15 === 0) {
echo "FizzBuzz\n";
} elseif ($i % 3 === 0) {
echo "Fizz\n";
} elseif ($i % 5 === 0) {
echo "Buzz\n";
} else {
echo $i . "\n";
}
}
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
The check for 15 comes first, because 15 is also a multiple of 3 and 5.
A product list in HTML
<?php
$products = [
["name" => "Notebook", "price" => 80],
["name" => "Pen", "price" => 12],
["name" => "Bag", "price" => 799],
];
echo "<ul>\n";
foreach ($products as $p) {
echo " <li>" . htmlspecialchars($p["name"]) . " - " . $p["price"] . "</li>\n";
}
echo "</ul>";
<ul>
<li>Notebook - 80</li>
<li>Pen - 12</li>
<li>Bag - 799</li>
</ul>
A shopping cart total
<?php
$cart = [
["name" => "Pen", "price" => 12, "qty" => 5],
["name" => "Book", "price" => 250, "qty" => 2],
];
$total = 0;
foreach ($cart as $line) {
$lineTotal = $line["price"] * $line["qty"];
echo "{$line['name']} x {$line['qty']} = $lineTotal\n";
$total += $lineTotal;
}
echo "Total: $total";
Pen x 5 = 60
Book x 2 = 500
Total: 560
Count words
<?php
$text = "the cat and the hat and the bat";
$counts = [];
foreach (explode(" ", $text) as $word) {
$counts[$word] = ($counts[$word] ?? 0) + 1;
}
print_r($counts);
Array
(
[the] => 3
[cat] => 1
[and] => 2
[hat] => 1
[bat] => 1
)
Prime numbers up to 30
<?php
for ($n = 2; $n <= 30; $n++) {
$isPrime = true;
for ($d = 2; $d * $d <= $n; $d++) {
if ($n % $d === 0) {
$isPrime = false;
break;
}
}
if ($isPrime) {
echo $n . " ";
}
}
2 3 5 7 11 13 17 19 23 29
Exercise: even numbers sum
Add all the even numbers from 1 to 20 and print the total.
Show a possible solution
<?php
$sum = 0;
for ($i = 2; $i <= 20; $i += 2) {
$sum += $i;
}
echo $sum;
110