Skip to content
Advertisement

How can I remove division by zero message in php and also improve my code?

Hello i am a complete beginner , I only know fundamentals of Html,CSS and PHP, what can I do to fix this issue (division by zero error and https://prnt.sc/1p4kw8a )and also to improve my code .the second issue is apparent when I submit it with empty textboxes Thank you in advance

<!DOCTYPE HTML>
<html>
<head> <meta charset="utf-8">

<title> Calculator </title>
</head>
<body>
<form action="calculator.php" method="post">
 Firt number - <input type="number" step="0.1" id="number1" name="number1"><br>
 Second number - <input type="number" step="0.1" id="number2" name="number2"><br>
 Option - <select name="operator">
     <option value="add" name="gruppe1">+</option>
     <option value="subtract" name="gruppe1">-</option>
     <option value="times" name="gruppe1" >x</option>
     <option value="divide" name="gruppe1">/</option>
     <option value="caret" name="gruppe1">^</option>
</select><br>
<input type="submit">
</form>

 <?php 
 $gruppe1 = $_POST["operator"];
 $number1 = $_POST["number1"];
 $number2 = $_POST["number2"];
 if($_POST["operator"] == "add"){
    echo $number1 + $number2;
 } elseif($_POST["operator"] == "subtract"){
    echo $number1 - $number2;
 } elseif($_POST["operator"] == "times"){
    echo  $number1 * $number2;
 } elseif($_POST["operator"] == "divide"){
   echo $number1 / $number2;
 } elseif($_POST["operator"] == "caret"){
    echo  $number1 ** $number2;
} 
 
 
   

 ?>
 
 
</body>
</html>

Advertisement

Answer

<!DOCTYPE HTML>
<html>
<head> <meta charset="utf-8">
<title> Calculator </title>
</head>
<body>
<form action="calculator.php" method="post">
Firt number - <input type="number" step="0.1" id="number1" name="number1"><br>
Second number - <input type="number" step="0.1" id="number2" name="number2"><br>
Option - <select name="operator">
<option value="add" name="gruppe1">+</option>
<option value="subtract" name="gruppe1">-</option>
<option value="times" name="gruppe1" >x</option>
<option value="divide" name="gruppe1">/</option>
<option value="caret" name="gruppe1">^</option>
</select><br>
<input type="submit">
</form>
<?php 
$gruppe1 = $_POST["operator"];
$number1 = $_POST["number1"];
$number2 = $_POST["number2"];
if($_POST["operator"] == "add"){
    echo $number1 + $number2;
} elseif($_POST["operator"] == "subtract"){
    echo $number1 - $number2;
} elseif($_POST["operator"] == "times"){
    echo  $number1 * $number2;
} elseif($_POST["operator"] == "divide"){
    echo $result = $number2 != 0 ? $number1 / $number2 : "Error";
} elseif($_POST["operator"] == "caret"){
    echo  $number1 ** $number2;
} 
?> 
</body>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement