我正在用PHP制作一个简单的计算器,并希望为除以0创建验证。
当用户除以零时,PHP会发出警告警告:在中除以零
我知道如果用户在做除法,我需要检查y==0,但我不确定该把它放在代码中的哪里。
<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>
我会把它放在除法情况下的switch语句中,
case "/":
echo $y==0 ? 'Illegal divisor' : ($x / $y);
break;
这将确保代码的可读性。
如果你不熟悉三元运算符,这里有语法:
{condtion}?{true语句}:{false语句}