create calculator in php

To create a simple calculator in PHP, follow these steps:

  1. Create an HTML form that accepts the first number, second number, and the arithmetic operation to be performed.
<form action="calculator.php" method="post">
  <label>First Number:</label>
  <input type="text" name="num1"><br><br>
  <label>Second Number:</label>
  <input type="text" name="num2"><br><br>
  <label>Operation:</label>
  <select name="operator">
    <option value="add">Addition</option>
    <option value="sub">Subtraction</option>
    <option value="mul">Multiplication</option>
    <option value="div">Division</option>
  </select><br><br>
  <input type="submit" value="Calculate">
</form>
494 chars
15 lines
  1. Create a PHP file and retrieve the user input from the form using the POST method. Then, perform the arithmetic operation based on the user-selected operator and output the result.
main.php
<?php
  if(isset($_POST['operator'])){
      $num1 = $_POST['num1'];
      $num2 = $_POST['num2'];
      $operator = $_POST['operator'];
      
      switch($operator){
        case "add":
          $result = $num1 + $num2;
          break;
        case "sub":
          $result = $num1 - $num2;
          break;
        case "mul":
          $result = $num1 * $num2;
          break;
        case "div":
          $result = $num1 / $num2;
          break;
        default:
          $result = 0;
       }
       echo "Result: ".$result;
    }
?>
547 chars
26 lines

This will create a basic calculator in PHP that can perform four different arithmetic operations.

gistlibby LogSnag