Skip to content

Simple PHP calculator

Sure! Here is a simple calculator implemented in PHP:

Example of a simple PHP calculator

php
<?php

// Check if the form has been submitted
if (isset($_POST['submit'])) {
  // Get the values from the form
  $num1 = $_POST['num1'];
  $num2 = $_POST['num2'];
  $operator = $_POST['operator'];

  // Check which operator was chosen and perform the corresponding calculation
  if ($operator == 'add') {
    $result = $num1 + $num2;
  } elseif ($operator == 'subtract') {
    $result = $num1 - $num2;
  } elseif ($operator == 'multiply') {
    $result = $num1 * $num2;
  } elseif ($operator == 'divide') {
    if ($num2 != 0) {
      $result = $num1 / $num2;
    } else {
      $result = "Error: Division by zero";
    }
  } else {
    $result = "Error: Invalid operator";
  }
} ?>

<form action="calculator.php" method="post">
  <input type="text" name="num1">
  <select name="operator">
    <option value="add">+</option>
    <option value="subtract">-</option>
    <option value="multiply">*</option>
    <option value="divide">/</option>
  </select>
  <input type="text" name="num2">
  <input type="submit" name="submit" value="Calculate">
</form>

<?php // If the form has been submitted, display the result
if (isset($result)) {
  echo "Result: " . htmlspecialchars($result);
}
?>

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

This code creates a simple form with two text inputs for the numbers and a dropdown menu for the operator. When the form is submitted, the PHP code retrieves the values from the form and performs the appropriate calculation. Finally, it displays the result on the page.

To run this example, save the code in a file named calculator.php and start a local PHP server (e.g., php -S localhost:8000), then open http://localhost:8000/calculator.php in your browser.

I hope this helps! Let me know if you have any questions.

Dual-run preview — compare with live Symfony routes.