Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 48

Calculator in PHP using switch Case

In this lesson: Simple PHP calculator using HTML form and switch case — add, subtract, multiply, divide with output.

What we are building

A calculator takes two numbers and an operator (+, -, *, /) and returns the result. It is a perfect small project to practise the switch statement, which chooses one action from several based on the operator. We will build it step by step and handle divide by zero safely.

💡 A switch is ideal here because we compare one value (the operator) against several exact options.

The switch logic

<?php
  $a = 10; $b = 5; $op = "+";
  switch ($op) {
      case "+": echo $a + $b; break;
      case "-": echo $a - $b; break;
      case "*": echo $a * $b; break;
      case "/": echo $a / $b; break;
      default:  echo "Invalid operator";
  }
?>
15

The switch matches $op to a case and runs that operation. Each case ends with break so only the matching one runs; default catches unknown operators.

The full calculator

<?php
  function calculate($a, $b, $op) {
      switch ($op) {
          case "+": return $a + $b;
          case "-": return $a - $b;
          case "*": return $a * $b;
          case "/":
              if ($b == 0) return "Cannot divide by zero";
              return $a / $b;
          default:  return "Invalid operator";
      }
  }
  echo calculate(20, 4, "/");   // 5
?>
5

Wrapping it in a function makes it reusable. Notice the divide case checks for zero first, returning a message instead of crashing.

Adding a form

<form method="post">
  <input type="number" name="a">
  <select name="op">
    <option>+</option><option>-</option>
    <option>*</option><option>/</option>
  </select>
  <input type="number" name="b">
  <button>Calculate</button>
</form>

<?php
  if ($_SERVER["REQUEST_METHOD"] === "POST") {
      $a = (float)$_POST["a"];
      $b = (float)$_POST["b"];
      echo calculate($a, $b, $_POST["op"]);
  }
?>

The form sends two numbers and the operator. We cast the numbers with (float) and pass everything into our calculate function.

Handling divide by zero

Dividing by zero must be handled or it errors. Our function checks if ($b == 0) first. In modern PHP you could also catch it:

<?php
  try {
      echo 10 / 0;
  } catch (DivisionByZeroError $e) {
      echo "Cannot divide by zero";
  }
?>
Cannot divide by zero

Either approach avoids a crash and shows a clear message to the user.

Common mistakes

  • Forgetting break. Without it, later cases run too (fall-through).
  • Not checking divide by zero. Always guard the division.
  • Not casting form values. Cast to (float) or (int) before maths.
  • No default case. Handle unknown operators with default.

Summary

  • A calculator picks an operation based on the operator — perfect for switch.
  • Each case does one operation and ends with break (or return).
  • Guard the divide case against zero.
  • Take input from a form and cast numbers before calculating.
  • Use default for invalid operators.

Next, review the concept in if-else and switch, or reuse logic with PHP functions.

Frequently Asked Questions

Why use a switch for a calculator?
A calculator picks one action from several based on the operator (+, -, *, /). A switch matches the operator to the right case cleanly, which is easier to read than a long chain of if-else statements.
How do I handle divide by zero in PHP?
Before dividing, check if the divisor is zero, or wrap the division in a try-catch for the DivisionByZeroError. Show a friendly message like "cannot divide by zero" instead of letting the program crash.
Why does each case need a break?
Without break, PHP keeps running the following cases too (fall-through). Adding break at the end of each case makes sure only the matching operation runs.
How do I take the operator from a user?
Use a form with a select or text input named like "op", then read it with $_POST["op"]. Pass that value into the switch to choose the operation.
What does default do in the switch?
The default case runs when the operator does not match any known case — for example an invalid symbol. It is a good place to show an "invalid operator" message.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicAJAX Live Search Your progress: 48 / 50 (96%) · Lesson 49 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free