exercises and solutions
Function exercises
Function exercises should make inputs, outputs, and failure behaviour explicit. Prefer a returned value that callers can use or test; print inside a function only when output is the function's responsibility.
Practical Example
<?php
declare(strict_types=1);
function lineTotal(int $pricePence, int $quantity): int
{
return $pricePence * $quantity;
}
echo lineTotal(499, 3) . PHP_EOL;
// Prints:
// 1497
Function exercises should ask learners to name inputs, return a value, and keep printing outside the function unless the function's job is output.
Extend exercises with a guard or type decision once the basic calculation works. A junior developer should be able to explain which layer rejects invalid input.
Practice
Write A Safe Line-Total Function
Show solution
Validate the quantity inside the function, throw InvalidArgumentException below one, and return $pricePence * $quantity. Printing lineTotal(499, 3) should produce 1497.
Keeping output outside the function makes the calculation easier to reuse and test.
Normalise A Product Name
Show solution
Trim first, reject '' with InvalidArgumentException, then return ucwords(strtolower($name)). Printing the result for " desk lamp " should produce Desk Lamp.
The guard belongs after trimming because whitespace-only input is not a useful product name.