Share icon

Simple calculator program in PHP that performs basic arithmetic operations:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $num1 = $_POST['num1'];
    $num2 = $_POST['num2'];
    $operator = $_POST['operator'];

    $result = '';

    switch ($operator) {
        case '+':
            $result = $num1 + $num2;
            break;
        case '-':
            $result = $num1 - $num2;
            break;
        case '*':
            $result = $num1 * $num2;
            break;
        case '/':
            if ($num2 != 0) {
                $result = $num1 / $num2;
            } else {
                $result = 'Cannot divide by zero';
            }
            break;
        default:
            $result = 'Invalid operator';
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Calculator</title>
</head>
<body>
    <h2>Calculator</h2>
    <form method="POST" action="">
        <input type="number" name="num1" required>
        <select name="operator">
            <option value="+">+</option>
            <option value="-">-</option>
            <option value="*">*</option>
            <option value="/">/</option>
        </select>
        <input type="number" name="num2" required>
        <input type="submit" value="Calculate">
    </form>

    <?php if (isset($result)) : ?>
        <h4>Result: <?php echo $result; ?></h4>
    <?php endif; ?>
</body>
</html>

This PHP script displays a simple HTML form where you can enter two numbers and select an operator. After submitting the form, the script retrieves the input values, performs the corresponding arithmetic operation based on the selected operator, and displays the result below the form.

Note: its just a basic example can't be use on production prupose.

Add new comment

Restricted HTML