Hello!

BrainTech - software solutions, web design and applications.

Contact

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

  1. Create an HTML form with fields broj1, broj2, and a select for operacija.
  2. Handle the POST request at the top of the file; sanitize input with filter_input.
  3. Implement switch by operation; check for division by zero.
  4. 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

  1. Open the project in htdocs/php-kurs.
  2. Implement the task from the lesson title: Exercise: mini calculator.
  3. Test the happy path and at least one invalid input.
  4. Check for errors in the browser and in php_error.log.
Design Wireframe
High Fidelity Design
Design development
Design development
Design development
Research development