Module 2 – PHP Fundamentals
Exercise
Exercise: Mini Calculator
Mini calculator in PHP
In this exercise you combine forms, if/switch, and basic operations on a single kalkulator.php page. The user enters two numbers and selects an operation (+, -, *, /). Display the result below the form with an error message for division by zero.
Goal
Build a functional web calculator with input validation and a clear result display.
Steps
- Create an HTML form with fields broj1, broj2, and a select for operacija.
- Handle the POST request at the top of the file; sanitize input with filter_input.
- Implement switch by operation; check for division by zero.
- Display the result in an alert-success div; retain entered values in the fields.
Criteria
- The form works exclusively with the POST method.
- Displays a meaningful error for empty input and division by zero.
- Code is split into logic at the top and HTML display below.
<?php
$a = filter_input(INPUT_POST, "a", FILTER_VALIDATE_FLOAT);
$op = $_POST["op"] ?? "+";
if ($a !== false && $b !== false) {
$rez = match ($op) { "+"=>$a+$b, "-"=>$a-$b, "*"=>$a*$b, "/"=> $b!=0 ? $a/$b : null };
}Exercise steps
- Open the project in
htdocs/php-kurs. - Implement the task from the lesson title: Exercise: mini calculator.
- Test the happy path and at least one invalid input.
- Check for errors in the browser and in
php_error.log.
