How to make a simple PHP calculator

Learn how to create a basic calculator in PHP using an example!

Creating a Simple Calculator with PHP

PHP (Hypertext Preprocessor) is a scripting language designed for web development, but it can also be used to create a simple calculator. In this tutorial, we will create a simple calculator that can add, subtract, multiply and divide two numbers. We will also use HTML and CSS to design a basic user interface.

First, we will create a simple HTML form that will take two numbers as inputs. We will create an input field for each number and a submit button to send the data to the server.


<form action="calculator.php" method="post">
  <input type="text" name="num1">
  <input type="text" name="num2">
  <input type="submit" name="submit" value="Calculate">
</form>

Next, we will create a PHP script called “calculator.php” to process the form data. This script will check if the form has been submitted, get the two numbers, determine the operation to be performed, and then display the result.


if (isset($_POST['submit'])) {
  // get the values from the form
  $num1 = $_POST['num1'];
  $num2 = $_POST['num2'];

  // determine the operation
  if ($_POST['submit'] == 'Add') {
    $result = $num1 + $num2;
  }
  if ($_POST['submit'] == 'Subtract') {
    $result = $num1 - $num2;
  }
  if ($_POST['submit'] == 'Multiply') {
    $result = $num1 * $num2;
  }
  if ($_POST['submit'] == 'Divide') {
    $result = $num1 / $num2;
  }

  // display the result
  echo $result;
}

Finally, we will create a basic user interface to display the form and the result. We will use HTML and CSS to style the page.


<html>
  <head>
    <title>Simple Calculator</title>
    <style type="text/css">
      body {
        font-family: Arial;
        font-size: 14px;
      }
      #container {
        width: 400px;
        margin: 0 auto;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <h1>Simple Calculator</h1>
      <form action="calculator.php" method="post">
        <input type="text" name="num1">
        <input type="text" name="num2">
        <input type="submit" name="submit" value="Add">
        <input type="submit" name="submit" value="Subtract">
        <input type="submit" name="submit" value="Multiply">
        <input type="submit" name="submit" value="Divide">
      </form>
      <?php
        if (isset($result)) {
          echo '<p>Result: <strong>'.$result.'</strong></p>';
        }
      ?>
    </div>
  </body>
</html>

And that's it! We have created a simple calculator with PHP, HTML, and CSS. You can now try it out by entering two numbers and clicking one of the buttons to perform the desired operation.

Answers (0)