0
0
PhpProgramBeginner · 2 min read

PHP Program to Create Simple Calculator

A simple PHP calculator can be created by taking two numbers and an operator as input, then using if or switch to perform addition, subtraction, multiplication, or division, like if ($op == '+') { $result = $num1 + $num2; }.
📋

Examples

Inputnum1=5, num2=3, op='+'
OutputResult: 8
Inputnum1=10, num2=2, op='/'
OutputResult: 5
Inputnum1=7, num2=0, op='/'
OutputError: Division by zero
🧠

How to Think About It

To build a simple calculator, first get two numbers and the operation from the user. Then check which operation they want using if or switch. Perform the calculation accordingly. Handle special cases like division by zero to avoid errors.
📐

Algorithm

1
Get the first number from the user
2
Get the second number from the user
3
Get the operator (+, -, *, /) from the user
4
Check the operator and perform the corresponding calculation
5
If division is chosen, check if the second number is zero to avoid error
6
Display the result or an error message
💻

Code

php
<?php
$num1 = 10;
$num2 = 5;
$op = '+';

if ($op == '+') {
    $result = $num1 + $num2;
} elseif ($op == '-') {
    $result = $num1 - $num2;
} elseif ($op == '*') {
    $result = $num1 * $num2;
} elseif ($op == '/') {
    if ($num2 == 0) {
        echo "Error: Division by zero";
        exit;
    }
    $result = $num1 / $num2;
} else {
    echo "Invalid operator";
    exit;
}
echo "Result: $result";
?>
Output
Result: 15
🔍

Dry Run

Let's trace the example where num1=10, num2=5, and op='+' through the code.

1

Assign values

num1 = 10, num2 = 5, op = '+'

2

Check operator

op is '+', so perform addition

3

Calculate result

result = 10 + 5 = 15

4

Output result

Print 'Result: 15'

StepOperationResult
1Assign num1=10, num2=5, op='+'
2Check if op == '+'True
3Calculate 10 + 515
4Print resultResult: 15
💡

Why This Works

Step 1: Input values

We start by assigning the two numbers and the operator to variables so the program knows what to calculate.

Step 2: Check operator

Using if and elseif, the program decides which math operation to perform based on the operator.

Step 3: Handle division by zero

Before dividing, the program checks if the second number is zero to avoid an error and prints a message if so.

Step 4: Display result

Finally, the program prints the result of the calculation to the screen.

🔄

Alternative Approaches

Using switch statement
php
<?php
$num1 = 8;
$num2 = 4;
$op = '*';
switch ($op) {
    case '+':
        $result = $num1 + $num2;
        break;
    case '-':
        $result = $num1 - $num2;
        break;
    case '*':
        $result = $num1 * $num2;
        break;
    case '/':
        if ($num2 == 0) {
            echo "Error: Division by zero";
            exit;
        }
        $result = $num1 / $num2;
        break;
    default:
        echo "Invalid operator";
        exit;
}
echo "Result: $result";
?>
Using <code>switch</code> can make the code cleaner and easier to read when checking multiple conditions.
Using functions for each operation
php
<?php
function add($a, $b) { return $a + $b; }
function subtract($a, $b) { return $a - $b; }
function multiply($a, $b) { return $a * $b; }
function divide($a, $b) {
    if ($b == 0) {
        return null;
    }
    return $a / $b;
}
$num1 = 7;
$num2 = 0;
$op = '/';
switch ($op) {
    case '+': $result = add($num1, $num2); break;
    case '-': $result = subtract($num1, $num2); break;
    case '*': $result = multiply($num1, $num2); break;
    case '/': $result = divide($num1, $num2); break;
    default: echo "Invalid operator"; exit;
}
if ($result === null) {
    echo "Error: Division by zero";
} else {
    echo "Result: $result";
}
?>
Using functions separates logic and makes the code reusable and easier to maintain.

Complexity: O(1) time, O(1) space

Time Complexity

The calculator performs a fixed number of operations without loops, so it runs in constant time O(1).

Space Complexity

It uses a few variables for input and output, so space usage is constant O(1).

Which Approach is Fastest?

All approaches (if-else, switch, functions) run in constant time; differences are mainly in readability and maintainability.

ApproachTimeSpaceBest For
If-ElseO(1)O(1)Simple quick checks
Switch StatementO(1)O(1)Cleaner multiple condition checks
FunctionsO(1)O(1)Reusable and maintainable code
💡
Always check for division by zero to avoid runtime errors in your calculator.
⚠️
Beginners often forget to handle division by zero, causing the program to crash or show wrong results.