Try each task first, then open the solution. Use only what you learned in this chapter.
Exercise 1: tip calculator
A bill is 840. Calculate a 12% tip and the total, and print both with two decimals.
Show a possible solution
<?php
$bill = 840;
$tip = $bill * 0.12;
$total = $bill + $tip;
echo "Tip: " . number_format($tip, 2) . "\n";
echo "Total: " . number_format($total, 2);
Tip: 100.80
Total: 940.80
Exercise 2: discount price
A product costs 2499. It has a 15% discount. Show the sale price rounded to the nearest whole number.
Show a possible solution
<?php
$price = 2499;
$discount = 15;
$sale = $price - ($price * $discount / 100);
echo round($sale);
2124
Exercise 3: average score
The scores are 72, 88, 95 and 61. Print the average with one decimal, the highest and the lowest.
Show a possible solution
<?php
$scores = [72, 88, 95, 61];
echo "Average: " . round(array_sum($scores) / count($scores), 1) . "\n";
echo "Highest: " . max($scores) . "\n";
echo "Lowest: " . min($scores);
Average: 79
Highest: 95
Lowest: 61
Exercise 4: how many pages?
There are 83 products and each page shows 12. How many pages do you need?
Show a possible solution
<?php
echo ceil(83 / 12);
7
Exercise 5: safe quantity
Write a function safeQuantity(string $input): int that turns the input into an integer between 1 and 10. If the input is not a whole number, return 1.
Show a possible solution
<?php
function safeQuantity(string $input): int
{
$value = filter_var(trim($input), FILTER_VALIDATE_INT);
if ($value === false) {
return 1;
}
return max(1, min(10, $value));
}
echo safeQuantity("7") . "\n";
echo safeQuantity("50") . "\n";
echo safeQuantity("abc");
7
10
1