Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
Can we use Arithmetic Operators ( + - * / ) in Switch Statement in PHP?

I was trying to make a calculator and wanted to use Arithmetic Operators in the switch Statement but i am not able to.

Can someone help me out.

Error:

Warning: Undefined array key "num2" in on line 16
220

Fatal error: Uncaught DivisionByZeroError: Division by zero in 27 Stack trace: #0 {main} thrown on line 27

<!DOCTYPE html>
<html>
<body>

<form action="php.php" method="post">
Number 1: <input type="number" name="num1"><br>
Operator: <input type="text" name="op"><br>
Number 3: <input type="number" name="num1"><br><br>

<input type="submit">
</form>

<?php
$num1 = $_POST["num1"];
$op = $_POST["op"];
$num2 = $_POST["num2"];
switch($op)
{
    case "+":
        echo $num1 + $num2;
    case "-":
        echo $num1 - $num2;
    case "*":
        echo $num1 * $num2;
    case "/":
        echo $num1 / $num2;         
}
?> 

</body>
</html>

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

<!DOCTYPE html>
<html>
<body>

<form action="php.php" method="GET">
Number 1: <input type="number" name="num1"><br>
Operator: <input type="text" name="op"><br>
Number 3: <input type="number" name="num2"><br><br>

<input type="submit">
</form>

<?php
$num1 = $_GET['num1'];
$op = $_GET['op'];
$num2 = $_GET['num2'];
    switch($op)
    {
        case '+':
            echo $num1 + $num2;
            break;
        case '-':
            echo $num1 - $num2;
            break;
        case '*':
            echo $num1 * $num2;
            break;
        case '/':
            echo $num1 / $num2;         
            break;
    }
?>

</body>
</html>

  1. Put break after every case
  2. These was a naming error in the code with the names of the variables. eg num1 and num2. Name them correctly
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!