PHP is a versatile scripting language often used for web development, but it can also be employed to create command-line applications. In this tutorial, we will guide you through the process of building a simple calculator script using PHP. This script will perform basic arithmetic operations such as addition, subtraction, multiplication, and division.


Before we get started, make sure you have PHP installed on your computer. You can download PHP from the official website ( or use a pre-installed package like XAMPP or WAMP.

Building the Calculator Script

  1. Create a New PHP FileOpen a text editor or an integrated development environment (IDE) and create a new PHP file. You can name it calculator.php.
  2. Write the PHP CodeAdd the following PHP code to your calculator.php file:

    // Check if the form has been submitted
    if (isset($_POST[‘submit’])) {
    // Get the user’s input
    $num1 = $_POST[‘num1’];
    $num2 = $_POST[‘num2’];
    $operator = $_POST[‘operator’];

    // Perform the calculation based on the selected operator
    switch ($operator) {
    case ‘add’:
    $result = $num1 + $num2;
    case ‘subtract’:
    $result = $num1 – $num2;
    case ‘multiply’:
    $result = $num1 * $num2;
    case ‘divide’:
    if ($num2 != 0) {
    $result = $num1 / $num2;
    } else {
    $result = ‘Division by zero is not allowed’;
    $result = ‘Invalid operator’;

    <!DOCTYPE html>
    <title>Simple Calculator</title>
    <h1>Simple Calculator</h1>
    <form method=”post” action=”calculator.php”>
    <input type=”number” name=”num1″ placeholder=”Enter first number” required>
    <select name=”operator”>
    <option value=”add”>+</option>
    <option value=”subtract”>-</option>
    <option value=”multiply”>*</option>
    <option value=”divide”>/</option>
    <input type=”number” name=”num2″ placeholder=”Enter second number” required>
    <input type=”submit” name=”submit” value=”Calculate”>
    // Display the result if available
    if (isset($result)) {
    echo ‘<h2>Result: ‘ . $result . ‘</h2>’;


    This PHP script takes user input for two numbers and an operator (addition, subtraction, multiplication, or division). It then calculates and displays the result.

  3. Testing the CalculatorSave the calculator.php file and open it in a web browser. You should see a simple calculator form. Enter values and select an operator, then click the “Calculate” button to see the result displayed on the page.


You’ve successfully created a basic calculator script using PHP. This script can perform common arithmetic operations and display the results to the user. You can further enhance this script by adding more features, such as handling decimal numbers or adding error handling for edge cases. PHP’s versatility makes it a great choice for building simple web-based applications like this calculator.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *