Try each exercise on your own first, then open the solution.
Exercise 1: age checker
Write code that prints Child for ages 0 to 12, Teen for 13 to 17, Adult for 18 to 64 and Senior for 65 and above. Test it with $age = 17.
Show a possible solution
<?php
$age = 17;
if ($age < 0) {
echo "Invalid age";
} elseif ($age <= 12) {
echo "Child";
} elseif ($age <= 17) {
echo "Teen";
} elseif ($age <= 64) {
echo "Adult";
} else {
echo "Senior";
}
Teen
Exercise 2: leap year
A year is a leap year if it can be divided by 4, except years divisible by 100, which must also be divisible by 400. Test 1900, 2000 and 2024.
Show a possible solution
<?php
function isLeapYear(int $year): bool
{
return ($year % 4 === 0 && $year % 100 !== 0) || $year % 400 === 0;
}
foreach ([1900, 2000, 2024] as $year) {
echo $year . ": " . (isLeapYear($year) ? "leap year" : "not a leap year") . "\n";
}
1900: not a leap year
2000: leap year
2024: leap year
Exercise 3: a day-of-week message with match
Given a number from 1 (Monday) to 7 (Sunday), print Weekday or Weekend. Use match.
Show a possible solution
<?php
$day = 6;
echo match ($day) {
1, 2, 3, 4, 5 => "Weekday",
6, 7 => "Weekend",
default => "Invalid day",
};
Weekend
Exercise 4: discount rule
Members get 10% off. Orders above 2000 get another 5% off. Print the final price for a member with a 2500 order.
Show a possible solution
<?php
$isMember = true;
$order = 2500;
$discount = 0;
if ($isMember) {
$discount += 10;
}
if ($order > 2000) {
$discount += 5;
}
$final = $order - ($order * $discount / 100);
echo "Discount: $discount%\n";
echo "Pay: $final";
Discount: 15%
Pay: 2125
Exercise 5: fix the bug
This code should print Pass for 50 or more and Fail below 50, but a mark typed as "0" is ignored, because "0" is falsy. Rewrite it so only a whole number from 0 to 100 is accepted, and test it with "0".
<?php
$mark = "0";
if ($mark) {
echo $mark >= 50 ? "Pass" : "Fail";
}
Show a possible solution
<?php
$mark = "0";
$value = filter_var($mark, FILTER_VALIDATE_INT, ["options" => ["min_range" => 0, "max_range" => 100]]);
if ($value === false) {
echo "Please enter a mark from 0 to 100";
} else {
echo $value >= 50 ? "Pass" : "Fail";
}
Fail