Current Location: Home> Latest Articles> PHP Tutorial: Easily Create a Simple Four-Operations Calculator

PHP Tutorial: Easily Create a Simple Four-Operations Calculator

gitbox 2025-08-10

Overview

Four basic arithmetic operations are common in everyday development. This article demonstrates how to implement a simple calculator using PHP for easy understanding and practical use.

Implementation Idea

The calculator implementation consists of the following steps:

  • Receive the user input expression;
  • Validate the expression for correctness;
  • Perform the arithmetic calculation;
  • Display the calculation result.

Implementation Steps

Receive User Input

Provide a web form for users to input the expression to be calculated. Example code:

<form action="" method="post">
    <label for="expression">Enter expression:</label>
    <input type="text" name="expression" id="expression">
    <input type="submit" value="Calculate">
</form>

The form uses POST method and label tags to improve user experience.

Expression Validation

After receiving the input, validate whether the expression is valid. Here, PHP's eval() function is used with the error suppression operator @ to prevent error messages from displaying.

<?php
$expression = $_POST['expression'];

// Calculate expression using eval
$result = @eval("return $expression;");

// Check if the expression is valid
if ($result === false) {
    echo 'Invalid expression';
} else {
    echo "Result: {$result}";
}
?>

Note that eval() has security risks; input should be sanitized or filtered carefully.

Perform Calculation

If the expression passes validation, calculate it directly with eval(), ensuring proper handling of operator precedence.

<?php
$expression = $_POST['expression'];
$result = @eval("return $expression;");
if ($result === false) {
    echo 'Invalid expression';
} else {
    echo "Result: {$result}";
}
?>

Output Result

Finally, display the calculated result to the user with an echo statement.

echo "Result: {$result}";

Summary

This article demonstrated how to quickly build a simple four-operations calculator in PHP. Although using eval() keeps the code concise, it comes with potential security concerns. Future improvements could include input filtering or using expression parsing libraries to enhance security and functionality.