Skip to content

PHP Tutorial Functions Exercise

Practice: Reusable Calculator Functions

Lesson 117 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Build small, reusable functions. Every function should have types and a clear name. Try each task first, then compare with the solution.

Exercise 1: tax and discount

Write addTax(float $price, float $rate = 18): float and applyDiscount(float $price, float $percent): float. Use both to calculate: 1000, 10% off, then 18% tax.

Show a possible solution
index.php
PHP
<?php
function addTax(float $price, float $rate = 18): float
{
    return $price * (1 + $rate / 100);
}

function applyDiscount(float $price, float $percent): float
{
    return $price * (1 - $percent / 100);
}

$final = addTax(applyDiscount(1000, 10));

echo $final;
Output
OUTPUT
1062

Exercise 2: average

Write average(float ...$numbers): float that returns the average of any number of values. If no values are given, return 0.

Show a possible solution
index.php
PHP
<?php
function average(float ...$numbers): float
{
    if ($numbers === []) {
        return 0;
    }

    return array_sum($numbers) / count($numbers);
}

echo average(70, 80, 90) . "\n";
echo average();
Output
OUTPUT
80
0

Exercise 3: a grade function

Write gradeFor(int $score): string that returns A for 90+, B for 75+, C for 60+ and F otherwise. Use match (true).

Show a possible solution
index.php
PHP
<?php
function gradeFor(int $score): string
{
    return match (true) {
        $score >= 90 => "A",
        $score >= 75 => "B",
        $score >= 60 => "C",
        default => "F",
    };
}

echo gradeFor(82) . gradeFor(40);
Output
OUTPUT
BF

Exercise 4: a formatter with a callback

Write formatAll(array $items, callable $formatter): array that applies the formatter to every item. Use it to wrap every word in <li> tags.

Show a possible solution
index.php
PHP
<?php
function formatAll(array $items, callable $formatter): array
{
    return array_map($formatter, $items);
}

$list = formatAll(["Tea", "Coffee"], fn($item) => "<li>$item</li>");

echo implode("", $list);
Output
OUTPUT
<li>Tea</li><li>Coffee</li>

Exercise 5: a counter with a closure

Write makeCounter(int $start = 0): callable that returns a function. Each call to that function returns the next number.

Show a possible solution
index.php
PHP
<?php
function makeCounter(int $start = 0): callable
{
    return function () use (&$start): int {
        return ++$start;
    };
}

$next = makeCounter(10);

echo $next() . " " . $next() . " " . $next();
Output
OUTPUT
11 12 13