How to Build a Simple PHP Calculator (With Line-by-Line Code Explanation)

Progressive PHP Full Course

⚙️ Your First Interactive PHP Project

In our previous modules, we learned about PHP Math Operators and Handling User Input. Today, we are going to combine these two fundamental concepts to build something real: a functional PHP Calculator. Instead of just giving you the final code, we will explain exactly how the frontend and backend talk to each other.

Explore the Full PHP Syllabus →

The Goal: Building a PHP Arithmetic Calculator

"Write a PHP script that receives two numbers from a user via an HTML form and calculates: the sum, the difference, the product, the quotient (division), and the remainder (modulo)."

Step-by-Step Code Explanation

To build this application properly, we need to understand the three distinct layers of our software. Let's break down the logic before looking at the final file.

1. The HTML Form (The Interface)

First, we need a way for the user to type their numbers. We use standard HTML for this.

<form action="home.php" method="GET">
    <input type="number" name="num1" step="any" required>
    <input type="number" name="num2" step="any" required>
    <input type="submit" value="Calculate">
</form>
  • action="home.php": This tells the browser to send the typed data to our PHP file named home.php.
  • method="GET": This sends the data through the URL, which is perfect for a simple calculator.
  • type="number" and step="any": This is a great UX (User Experience) practice. It forces the browser to only accept numbers (including decimals), preventing users from typing letters.

2. Capturing Data Securely (The Backend Bridge)

Once the user clicks "Calculate", PHP takes over. But what happens if the user visits the page for the very first time, before submitting any form? PHP would try to calculate numbers that don't exist yet, causing an error!

if(isset($_GET['num1']) && isset($_GET['num2'])) {
    $num1 = (float)$_GET['num1'];
    $num2 = (float)$_GET['num2'];
}
  • isset(): This is a built-in PHP function. It translates to: "Does this data exist?" We use it to wrap our logic so the math only happens IF the user actually submitted the form.
  • (float): This is called Type Casting. Even though the HTML field is a "number", everything sent via HTTP is technically text. By placing (float) before our variable, we forcefully convert the text into a decimal number, making our application much safer against malicious inputs.

3. Processing and Concatenating Data

Now that we have safe, clean numbers stored in $num1 and $num2, we need to do the math and display it.

echo "Addition: " . ($num1 + $num2) . "<br>";
  • The Dot (.): In PHP, the dot is used to glue (concatenate) strings and variables together.
  • Parentheses ($num1 + $num2): These are mandatory! They tell the PHP engine: "Hey, do the mathematical calculation inside these brackets first, and only then attach the result to the word 'Addition'."

The Complete Source Code (home.php)

Now that you understand the mechanics, create a file named home.php in your local server and paste the complete code below to see it in action.

<!DOCTYPE html>
<html>
<head>
    <title>My PHP Calculator</title>
</head>
<body style="font-family: Arial, sans-serif; margin: 40px;">

    <h2>PHP Math Calculator</h2>
    
    <form action="home.php" method="GET">
        <label>Number 1:</label>
        <input type="number" name="num1" step="any" required><br><br>
        
        <label>Number 2:</label>
        <input type="number" name="num2" step="any" required><br><br>
        
        <input type="submit" value="Calculate" style="padding: 10px 20px; cursor: pointer;">
    </form>
    
    <hr style="margin: 30px 0;">

    <?php 
        // Ensure the form was submitted
        if(isset($_GET['num1']) && isset($_GET['num2'])) {
            
            // Capture and sanitize inputs
            $num1 = (float)$_GET['num1'];
            $num2 = (float)$_GET['num2'];
            
            echo "<h3>Results:</h3>";
            
            // Output calculations
            echo "Addition: " . ($num1 + $num2) . "<br>";
            echo "Subtraction: " . ($num1 - $num2) . "<br>";
            echo "Multiplication: " . ($num1 * $num2) . "<br>";
            
            // Prevent Division by Zero Error
            if($num2 != 0) {
                echo "Division: " . ($num1 / $num2) . "<br>";
                echo "Modulo (Remainder): " . ($num1 % $num2) . "<br>";
            } else {
                echo "<span style='color: red; font-weight: bold;'>Error: You cannot divide by zero!</span><br>";
            }
        }
    ?>

</body>
</html>

💡 Expert Tip: Anticipate Errors (Division by Zero)

A good programmer doesn't just write code that works; they write code that doesn't break. In mathematics, dividing a number by zero is impossible. If a user types 0 in the second field and your PHP script tries to divide by it, PHP 8+ will throw a Fatal Error: Uncaught DivisionByZeroError and crash your entire application. That is why we wrapped the division block inside an if($num2 != 0) safety check!

Did you get your calculator running? Challenge: Try adding a third input field to calculate the average of three numbers! Post your updated code in the comments below.


Next Step: Controlling the Flow

You've just built an app that makes a decision (checking if the divisor is zero). This is called conditional logic. In the next module, we will dive deep into PHP If, Else, and Elseif Statements to give your applications true artificial intelligence!

Go to the Next Lesson in the Syllabus →

Nenhum comentário:

Veja também: