PHP
Project final - Calculator
Combine all parts and finalize a working calculator.
Final step: division by zero
In the final lesson we'll complete the calculator. So far we take two numbers, perform four operations with if/elseif, and catch invalid operators with an else branch.
The only missing piece is the division by zero guard. When the divisor is 0, the result is mathematically undefined; instead of letting the program crash, we should show an error message to the user.
Zero check with a nested if
For the division-by-zero guard we add a second if inside the division branch. If $second equals 0, we show an error message; otherwise we perform the division.
if ($second === 0) {
$result = "Error: division by zero";
} else {
$result = $first / $second;
}
This is a nested if: the outer elseif catches the division operator, the inner if checks for zero.
Exercise Add the division-by-zero guard
In the final step, add a division-by-zero guard. For the / operator, if $second equals 0, assign the message "Error: division by zero" to $result; otherwise perform the division. The calculator is now complete.
Show example solution
Add a zero check inside the division branch.
Example solution:
<?php
// The first number entered by the user
$first = 25;
// The chosen operator and second number
$operator = "+";
$second = 4;
$result = 0;
if ($operator === "+") {
$result = $first + $second;
} elseif ($operator === "-") {
$result = $first - $second;
} elseif ($operator === "*") {
$result = $first * $second;
} elseif ($operator === "/") {
// Check whether the divisor is zero
if ($second === 0) {
$result = "Error: division by zero";
} else {
$result = $first / $second;
}
} else {
$result = "Error: invalid operation";
}
echo "Result: " . $result;
Project complete
Congratulations! Your calculator is complete. Over five lessons you:
- declared two number variables and an operator
- computed the four operations with if/elseif
- caught invalid operators with an else branch
- guarded against division by zero
This project combined variables, conditionals and error handling in PHP. In the next section we'll dig deeper into operators.
Test yourself
-
What happens if the divisor is 0 in division?
- The result is 0
- A division by zero error is shown
- The operation is skipped
- The result is 1
Show answer
A division by zero error is shown — Division by zero is undefined, so an error message is shown.
-
Pick the right variable for the zero check
<?php
if ($operator === "/") {
if (____ === 0) {
$result = "Error: division by zero";
} else {
$result = $first / $second;
}
}
?>
Show answer
<?php
if ($operator === "/") {
if ($second === 0) {
$result = "Error: division by zero";
} else {
$result = $first / $second;
}
}
?>
-
Match each project piece to its lesson
- $first, $second
- Number input
- if/elseif
- Computation
- else branch
- Invalid operator
- Zero check
- Division error
Next lesson: Arithmetic operators