PHP
Challenge - Calculator
Build an advanced calculator with functions, loops and conditionals.
Challenge - Calculator
In this challenge you'll write a calculator function with typed parameters. Use the signature calculate(float $a, float $b, string $op) and pick the operation with an if/elseif chain.
For division you must guard against division by zero: if $b is zero, return an error string. An unknown operator should also return an error message. This brings together your beginner knowledge of functions, conditionals and validation.
Exercise Write the calculator function
Define calculate(float $a, float $b, string $op): float|string. Use if/elseif to pick +, -, *, /. For division, if $b == 0 return "Error: division by zero". For an unknown operator return "Error: unknown operation". Then add echo calculate(10, 5, "+") . "\n"; and echo calculate(10, 0, "/") . "\n";.
Show example solution
Write the signature as float $a, float $b, string $op; use if/elseif for +, -, *, /; in division check $b == 0.
Example solution:
<?php
// Write calculate and call it
function calculate(float $a, float $b, string $op): float|string {
if ($op === "+") {
return $a + $b;
} elseif ($op === "-") {
return $a - $b;
} elseif ($op === "*") {
return $a * $b;
} elseif ($op === "/") {
if ($b == 0) {
return "Error: division by zero";
}
return $a / $b;
}
return "Error: unknown operation";
}
echo calculate(10, 5, "+") . "\n";
echo calculate(10, 0, "/") . "\n";
Test yourself
-
What should calculate(10, 0, "/") return?
- 0
- Error: division by zero
- 10
- Infinity
Show answer
Error: division by zero — Correct. When $b is zero the function returns an error string, not a number.
-
Complete the division branch
function calculate(float $a, float $b, string $op): float|string {
if ($op === "+") { return $a + $b; }
if ($op === "-") { return $a - $b; }
if ($op === "*") { return $a * $b; }
____ ($op === "/") {
if ($b == 0) { return "Error: division by zero"; }
return $a / $b;
}
return "Error: unknown operation";
}
Show answer
function calculate(float $a, float $b, string $op): float|string {
if ($op === "+") { return $a + $b; }
if ($op === "-") { return $a - $b; }
if ($op === "*") { return $a * $b; }
elseif ($op === "/") {
if ($b == 0) { return "Error: division by zero"; }
return $a / $b;
}
return "Error: unknown operation";
}
-
Match each operator to its meaning
- +
- addition
- -
- subtraction
- *
- multiplication
- /
- division
Next lesson: Challenge - Secure feedback form