Write a simple calculator program in PHP using switch case

Description:

You need to write a simple calculator program in PHP using switch case.

Operations:

  • Addition
  • Subtraction
  • Multiplication
  • Division

View Solution/Program

<!DOCTYPE html>
 
<head>
	<title>Simple Calculator Program in PHP - Tutorials Class</title>
</head>
 
<?php
$first_num = $_POST['first_num'];
$second_num = $_POST['second_num'];
$operator = $_POST['operator'];
$result = '';
if (is_numeric($first_num) && is_numeric($second_num)) {
    switch ($operator) {
        case "Add":
           $result = $first_num + $second_num;
            break;
        case "Subtract":
           $result = $first_num - $second_num;
            break;
        case "Multiply":
            $result = $first_num * $second_num;
            break;
        case "Divide":
            $result = $first_num / $second_num;
    }
}
 
?>
 
<body>
    <div id="page-wrap">
	<h1>PHP - Simple Calculator Program</h1>
	  <form action="" method="post" id="quiz-form">
            <p>
                <input type="number" name="first_num" id="first_num" required="required" value="<?php echo $first_num; ?>" /> <b>First Number</b>
            </p>
            <p>
                <input type="number" name="second_num" id="second_num" required="required" value="<?php echo $second_num; ?>" /> <b>Second Number</b>
            </p>
            <p>
                <input readonly="readonly" name="result" value="<?php echo $result; ?>"> <b>Result</b>
            </p>
            <input type="submit" name="operator" value="Add" />
            <input type="submit" name="operator" value="Subtract" />
            <input type="submit" name="operator" value="Multiply" />
            <input type="submit" name="operator" value="Divide" />
	  </form>
    </div>
</body>
</html>
Tutorials Class - Output Window

simple-calculator-program-in-PHP-using-switch-case


Learn more about the similar topics:
Tutorials
PHP Decision Making
Exercises & Assignments
Write a program to check student grade based on marks
Write a program to show day of the week using switch
Write a program to calculate Electricity bill in PHP
Write a simple calculator program in PHP using switch case
Write a PHP program to check if a person is eligible to vote
Write a PHP program to check whether a number is positive, negative or zero
Interview Questions & Answers
No Content Found.