- PHP

Switch and Case Calculator in PHP

Switch statements are great for many operations where we want to change the script’s behavior depending on some value.

For this reason, they may be great for creating a simple calculator.

Here’s an example:

<form method="POST" action="">
    <input type="number" name="num1">
    <select name="operation">
        <option value="add">+</option>
        <option value="subtract">-</option>
        <option value="multiply">*</option>
        <option value="divide">/</option>
    </select>
    <input type="number" name="num2">

    <input type="submit" name="calculate">
</form>

<?php

if(isset($_POST['num1']) && isset($_POST['num2'])) {
    $num1 = $_POST['num1'];
    $num2 = $_POST['num2'];

    $result = 0;

    switch ($_POST['operation']) {
        case 'add':
            $result = $num1 + $num2;
            break;
        
        case 'subtract':
            $result = $num1 - $num2;
            break;

        case 'multiply':
            $result = $num1 * $num2;
            break;

        case 'divide':
            $result = $num1 / $num2;
            break;
    }

    echo '<b>Result:</b> ' . $result;
}

?>

Output:

Switch and Case PHP calculator