Write a simple calculator program in PHP using switch case

Description: Write a simple calculator program in PHP using the switch case.

Rules and hints:

  • Operations: addition, subtraction, multiplication and division.
  • Use an HTML form with two number fields and a select box for the operation.
  • Check that both values are numbers, and do not allow division by zero.

PHP simple calculator program

<?php
$result = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $first = $_POST["first_num"] ?? "";
    $second = $_POST["second_num"] ?? "";
    $operator = $_POST["operator"] ?? "";

    if (is_numeric($first) && is_numeric($second)) {
        switch ($operator) {
            case "Add":
                $result = $first + $second;
                break;
            case "Subtract":
                $result = $first - $second;
                break;
            case "Multiply":
                $result = $first * $second;
                break;
            case "Divide":
                $result = ($second == 0) ? "Cannot divide by zero" : $first / $second;
                break;
            default:
                $result = "Please select an operation";
        }
    } else {
        $result = "Please enter valid numbers";
    }
}
?>
<form method="post">
    <input type="text" name="first_num" value="<?php echo htmlspecialchars($_POST["first_num"] ?? ""); ?>">
    <select name="operator">
        <option>Add</option>
        <option>Subtract</option>
        <option>Multiply</option>
        <option>Divide</option>
    </select>
    <input type="text" name="second_num" value="<?php echo htmlspecialchars($_POST["second_num"] ?? ""); ?>">
    <button type="submit">Calculate</button>
</form>
<?php
if ($result !== "") {
    echo "<p>Result: " . htmlspecialchars((string) $result) . "</p>";
}
?>

Output:

When the numbers are 12 and 4 and the operation is Multiply

Result: 48

How it works

  • The PHP code at the top runs only when the form is sent with POST.
  • is_numeric() checks both values before the calculation.
  • switch selects the operation using the text of the select box.
  • The old values are put back in the fields, and htmlspecialchars() keeps the page safe from XSS.

Related: PHP Forms Handling.


Learn more about the similar topics:
Tutorials
PHP Decision Making
Exercises & Assignments
Write a program to check student grade based on marks
Write a program to show day of the week using switch
Write a program to calculate Electricity bill in PHP
Write a simple calculator program in PHP using switch case
Write a PHP program to check if a person is eligible to vote
Write a PHP program to check whether a number is positive, negative or zero
Interview Questions & Answers
No Content Found.