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.
The calculator implementation consists of the following steps:
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.
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.
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}";
}
?>
Finally, display the calculated result to the user with an echo statement.
echo "Result: {$result}";
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.