Validation for a Divide by Zero in PHP - php

I'm making a simple Calculator in PHP and want to create validation for a divide by 0.
At the moment when a user divides by zero, PHP issues the warning Warning: Division by zero in
I know I need to check if y == 0 if the user is doing division, but I'm unsure where to put it in my code.
<html>
<head>
<title>PHP Calculator</title>
</head>
<body>
<h3>PHP Calculator (Version 6)</h3>
<p>Add, subtract, divide or multiply and output the result</p>
<form method="get" action="<?php print $_SERVER['PHP_SELF']; ?>">
<input type = "number" name = "x" placeholder = "0" required>
<select name = "operator">
<option>None</option>
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type = "number" name = "y" placeholder = "0" required>
<input type="submit" name="submit" value="Calculate"/>
</form>
<p>The answer is: </p>
<?php
if (isset($_GET['submit'])) {
$x = $_GET['x'];
$y = $_GET['y'];
$operator = $_GET['operator'];
switch ($operator) {
case "+":
echo $x + $y;
break;
case "-":
echo $x - $y;
break;
case "*":
echo $x * $y;
break;
case "/":
echo $x / $y;
break;
default:
echo "You should to select a method!";
break;
}
}
?>
</body>
</html>

I would put it in the switch statement in division case,
case "/":
echo $y==0 ? 'Illegal divisor' : ($x / $y);
break;
This will ensure readability of your code.
If you're not familiar with the ternary operator here's the syntax:
{condtion} ? {true statement} : {false statement}

Related

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>
<!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>
Put break after every case
These was a naming error in the code with the names of the variables. eg num1 and num2. Name them correctly

A non numeric value encountered in ..... on line 35

This is the code that I'm using. All the arithemetic operations are done successfully except subtraction. When Subtraction is selected, it gives the error. If I use two different echo statements, one for "The answer is: " and the other echo statement for the subtraction between two variables, it gives no error. What is the reason behind the generation of this error when both the variables string are printed using one echo statement??
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form>
<input type="text" name="num1" placeholder="First Number">
<input type="text" name="num2" placeholder="Second Number">
<select name="operator">
<option>None</option>
<option>Add</option>
<option>Subtract</option>
<option>Multiply</option>
<option>Divide</option>
</select>
<br>
<button name="submit" value="submit">Calculate</button>
</form>
<?php
if (isset($_GET['submit'])) {
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$operator = $_GET['operator'];
switch ($operator) {
case "None":
echo "You need to set a method!";
break;
case 'Add':
echo "The answer is: ".$num1 + $num2;
break;
case 'Subtract':
echo "The answer is: ".$num1 - $num2;
break;
case 'Multiply':
echo "The answer is: ".$num1 * $num2;
break;
case 'Divide':
echo "The answer is: ".$num1 / $num2;
break;
}
}
?>
</body>
</html>
https://www.php.net/manual/en/language.operators.precedence.php
The . in your string concatenation has a higher operator precedence than your -. You should add parentheses around your $num expressions.
switch ($operator) {
case "None":
echo "You need to set a method!";
break;
case 'Add':
echo "The answer is: ".($num1 + $num2);
break;
case 'Subtract':
echo "The answer is: ". ($num1 - $num2);
break;
case 'Multiply':
echo "The answer is: ".($num1 * $num2);
break;
case 'Divide':
echo "The answer is: ".($num1 / $num2);
break;
}

How to set up multiple conditions by using switch?

I want to code a counting game on php.
The rule is like the following:
1. Player selects a number from 0~3
2. Computer selects a number from player's selection + 0~3
3. The one arrive 30 lose the game
The code I have written :
<?php
$total = $_POST['total'];
$user_number = $_POST['number']; // 1~3
$total='';
switch ($total){
case '4':
case '8':
case '12':
case '16':
case '20':
case '24':
case '28':
$computer_selection = 1;
break;
case '3':
case '7':
case '12':
case '16':
case '20':
case '23':
case '27':
$computer_selection = 2;
break;
case '2':
case '6':
case '11':
case '15':
case '19':
case '22':
case '26':
$computer_selection = 3;
break;
default:
$computer_selection =1;
break;
}
$computer_number = $total + $computer_selection;
$total = $user_number + $computer_number;
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>恐怖の30ゲーム</title>
</head>
<body>
<?php print_r('The choice of computer'.$computer_number.'<br>'); ?>
<?php print_r('Current number:'.$total.'<br>'); ?>
恐怖の30
<?php
$total_nubmer1=$total+1;
$total_number2=$total+2;
$total_number3=$total+3;
?>
<form method='post' action='index2.php'>
you:
<select name='number'></br>
<option value='<?php echo $total_nubmer1 ?>'><?php echo
$total_nubmer1 ?></option>
<option value='<?php echo $total_number2 ?>'><?php echo
$total_number2 ?></option>
<option value='<?php echo $total_number3 ?>'><?php echo
$total_number3 ?></option>
</select>
<input type='hidden' name='total' value='<?php $total?>'>
<input type='submit' value='登録'>
</form>
</body>
</html>
<?php
if ($user_number>=30){
echo "<script language=\"JavaScript\">alert(\"you lose\");location.href='index.php';</script>";
}else if($user_number<=29 && $user_number>28||$total>29){
echo "<script language=\"JavaScript\">alert(\"you win\");location.href='index.php'</script>";
}
?>
I dont't understand why the output at computer_selection always goes to default.
Because you put this : $total=''; just before the switch.
So, the $total always enter in the default case of your switch.
You are reassigning the value of $total before entering to the switch. Another thing that you are doing is assuming that the value of $total is recieved in the $_POST param, you shoul check if the value is set first. So remove the $total = ''; line and do something like this in your assignment
$total = (isset($_POST['total']))?$_POST['total']:'';
Same goes for number. That way if nothing is recieved it will go default.
Hope it helps!

Quadratic equation solver in php

I tried to make a quadratic equation solver in php:
index.html:
<html>
<body>
<form action="findx.php" method="post">
Find solution for ax^2 + bx + c<br>
a: <input type="text" name="a"><br>
b: <input type="text" name="b"><br>
c: <input type="text" name="c"><br>
<input type="submit" value="Find x!">
</form>
</body>
</html>
findx.php:
<?php
if(isset($_POST['a'])){ $a = $_POST['a']; }
if(isset($_POST['b'])){ $b = $_POST['b']; }
if(isset($_POST['c'])){ $c = $_POST['c']; }
$d = $b*$b - 4*$a*$c;
echo $d;
if($d < 0) {
echo "The equation has no real solutions!";
} elseif($d = 0) {
echo "x = ";
echo (-$b / 2*$a);
} else {
echo "x1 = ";
echo ((-$b + sqrt($d)) / (2*$a));
echo "<br>";
echo "x2 = ";
echo ((-$b - sqrt($d)) / (2*$a));
}
?>
the problem is that it's returning wrong answers (d is right,x1 and x2 are not) seems like sqrt() is returning zero or maybe something else.
There's a typo in this line:
elseif($d = 0)
which is assigning the value 0 to $d instead of comparing it. That means you are always evaluating sqrt(0), which is 0, in your else block.
It should be:
elseif($d == 0)

PHP Calculator that will continuously compute

The only remaining issue is that when I try and complete a second computation using the value from the previous calculation as the beginning value, the answer is always 0. What else needs to be done in order to just continuously compute equations?
<html>
<?php
session_start();
$_SESSION['num1']= 0;
$num1 = $_SESSION['num1'];
if(isset($_POST['num1'])){
$num1 = $_POST['num1'];
}
if(isset($_POST['num2'])){
$num2 = $_POST['num2'];
}
if(isset($_POST['calcu'])){
$calcu = $_POST['calcu'];
}
function calculate($n1,$n2,$calcu){
switch($calcu)
{
case "Addition":
$compute = $n1 + $n2;
break;
case "Subtraction":
$compute = $n1 - $n2;
break;
case "Multiplication":
$compute = $n1 * $n2;
break;
case "Division":
$compute = $n1 / $n2;
break;
}
return $compute;
}
// echo "$calcu <br /> <br /> Beginning Number: $num1 <br /> Next Number: $num2 <br /><br />";
echo "Answer is:" .calculate($num1,$num2, $calcu);
$_SESSION['num1']=calculate($num1, $num2, $calcu);
?>
<body>
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
Beginning Number:<?php echo $_SESSION['num1'];?><br>
Next Number: <input type="number"name="num2"><br>
Calculation: Please type one of the following- Addition, Subtraction, Multiplication, or Division. <input type="text" name="calcu"><br>
<input type="submit"><br>
</form>
</body>
</html>
From your code:
$_SESSION['num1']= 0;
$num1 = $_SESSION['num1'];
Since you've just assigned 0 to $_SESSION['num1'], $num1 will always end up zero as well.
You probably want to wrap that first assignment in a conditional:
if (!isset($_SESSION['num1'])) {
$_SESSION['num1'] = 0;
}

Categories