- PHP

How to check which button is clicked in PHP

Our form may have more than one button. If they are used to performing different things, you will have to check which button was clicked before starting the validation.

To check which button was clicked, use the isset() function.

Remember to grant these buttons their names with name=””.

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (isset($_POST['btnCancel'])) {
    // perform an action if the btnCancel was clicked
  } else if(isset($_POST['btnSubmit'])) {
    // perform an action if the btnSubmit was clicked
  }
}

?>

Example:

Make a simple calculator in PHP with operation depending on the clicked button.

<form action="" method="POST">
  <label><b>Number 1:</b></label>
  <br><br>
  <input type="text" name="number1" value="<?php if(isset($_POST['number1'])) { echo $_POST['number1']; } ?>">
  <br><br>
  <label><b>Number 2:</b></label>
  <br><br>
  <input type="text" name="number2" value="<?php if(isset($_POST['number2'])) { echo $_POST['number2']; } ?>">
  <br><br>
  <button type="submit" name="add">Add (+)</button>
  <button type="submit" name="subtract">Subtract (-)</button>
</form>

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $number1 = $_POST['number1'];
  $number2 = $_POST['number2'];

  if (isset($_POST['add'])) {
    echo $number1 . ' + ' . $number2 . ' = ' . $number1 += $number2;
  } else if(isset($_POST['subtract'])) {
    echo $number1 . ' - ' . $number2 . ' = ' . $number1 -= $number2;
  }
}

?>

Output:

Simple PHP calculator