Here’s a simple Calculator in PHP that performs arithmetic operations like addition, subtraction, multiplication, and division, along with an explanation of the code.
Table of Contents
Project Description
This PHP calculator will:
Allow the user to input two numbers.
Allow the user to select an arithmetic operation (addition, subtraction, multiplication, division).
Perform the selected operation on the numbers and display the result.
Complete Code
<?php // Initialize variables $result = ""; $error_message = ""; // Check if the form was submitted if (isset($_POST['submit'])) { // Retrieve the input numbers and operator from the form $number1 = $_POST['number1']; $number2 = $_POST['number2']; $operator = $_POST['operator']; // Validate that the input numbers are numeric if (is_numeric($number1) && is_numeric($number2)) { // Perform the chosen arithmetic operation switch ($operator) { case "add": $result = $number1 + $number2; // Addition break; case "subtract": $result = $number1 - $number2; // Subtraction break; case "multiply": $result = $number1 * $number2; // Multiplication break; case "divide": // Check for division by zero if ($number2 != 0) { $result = $number1 / $number2; // Division } else { $error_message = "Error: Division by zero is not allowed!"; } break; default: $error_message = "Invalid operator selected."; } } else { $error_message = "Please enter valid numeric values."; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Basic Calculator</title> </head> <body> <h1>PHP Basic Calculator</h1> <!-- Display error message if any --> <?php if ($error_message): ?> <p style="color: red;"><?php echo $error_message; ?></p> <?php endif; ?> <!-- Calculator form for input --> <form method="post" action=""> <label for="number1">Enter First Number:</label> <input type="text" name="number1" required value="<?php echo isset($number1) ? $number1 : ''; ?>"> <br><br> <label for="number2">Enter Second Number:</label> <input type="text" name="number2" required value="<?php echo isset($number2) ? $number2 : ''; ?>"> <br><br> <label for="operator">Select Operation:</label> <select name="operator" required> <option value="add" <?php echo isset($operator) && $operator == "add" ? 'selected' : ''; ?>>Add (+)</option> <option value="subtract" <?php echo isset($operator) && $operator == "subtract" ? 'selected' : ''; ?>>Subtract (-)</option> <option value="multiply" <?php echo isset($operator) && $operator == "multiply" ? 'selected' : ''; ?>>Multiply (×)</option> <option value="divide" <?php echo isset($operator) && $operator == "divide" ? 'selected' : ''; ?>>Divide (÷)</option> </select> <br><br> <button type="submit" name="submit">Calculate</button> </form> <!-- Display the result if available --> <?php if ($result !== ""): ?> <h2>Result: <?php echo $result; ?></h2> <?php endif; ?> </body> </html>
Explanation of the Code
1. Form Submission and Input Processing
if (isset($_POST['submit'])) { $number1 = $_POST['number1']; $number2 = $_POST['number2']; $operator = $_POST['operator']; }
This section checks if the form has been submitted by checking if the submit button is clicked (isset($_POST[‘submit’])).
It retrieves the user input: the two numbers ($_POST[‘number1’], $_POST[‘number2’]) and the selected operator ($_POST[‘operator’]).
2. Input Validation
if (is_numeric($number1) && is_numeric($number2)) {
This validates whether both numbers entered by the user are numeric using the is_numeric() function. If the inputs are valid, the script proceeds to the calculation part; otherwise, an error message is shown.
3. Performing Arithmetic Operations
switch ($operator) { case "add": $result = $number1 + $number2; // Addition break; case "subtract": $result = $number1 - $number2; // Subtraction break; case "multiply": $result = $number1 * $number2; // Multiplication break; case "divide": if ($number2 != 0) { $result = $number1 / $number2; // Division } else { $error_message = "Error: Division by zero is not allowed!"; } break; default: $error_message = "Invalid operator selected."; }
Based on the operator selected by the user, the script performs one of the following operations:
Addition (+): Adds the two numbers.
Subtraction (-): Subtracts the second number from the first.
Multiplication (*): Multiplies the two numbers.
Division (/): Divides the first number by the second. It also checks if the second number is not zero to avoid division by zero errors.
If the operator is invalid, it displays an error message.
4. Displaying the Result or Error Message
<?php if ($result !== ""): ?> <h2>Result: <?php echo $result; ?></h2> <?php endif; ?>
If the result is successfully calculated, it will be displayed below the form in an <h2> tag.
If there’s an error (e.g., non-numeric input or division by zero), an error message will be displayed.
5. HTML Form
<form method="post" action=""> <label for="number1">Enter First Number:</label> <input type="text" name="number1" required> <br><br> <label for="number2">Enter Second Number:</label> <input type="text" name="number2" required> <br><br> <label for="operator">Select Operation:</label> <select name="operator" required> <option value="add">Add (+)</option> <option value="subtract">Subtract (-)</option> <option value="multiply">Multiply (×)</option> <option value="divide">Divide (÷)</option> </select> <br><br> <button type="submit" name="submit">Calculate</button> </form>
This HTML form contains:
Two input fields for the numbers.
A dropdown menu for selecting the arithmetic operation (addition, subtraction, multiplication, division).
A submit button to process the form.
The form uses the POST method to send the data to the same PHP file for processing.
How the Calculator Works
User Input: The user enters two numbers and selects an operation (addition, subtraction, multiplication, or division).
Form Submission: When the user clicks the “Calculate” button, the form data is sent to the PHP script via POST.
Validation: The script validates that both input values are numeric and checks for division by zero if division is selected.
Calculation: The selected arithmetic operation is performed, and the result is stored.
Result Display: The result (or an error message) is displayed on the webpage.
Potential Improvements
Add More Operations: You could add more operations like modulus, exponentiation, or square root.
Styling: Use CSS to improve the look and feel of the calculator form.
JavaScript Validation: You can add client-side validation using JavaScript to ensure users input valid numbers before submitting the form.
This simple PHP calculator project helps you practice form handling, input validation, conditional logic (using switch), and basic arithmetic operations.