switch
语句执行相应的操作,并在页面上显示结果。注意确保输入的数字是有效的,否则可能会导致错误。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP Calculator</title>
</head>
<body>
<form method="post">
<input type="text" name="num1" placeholder="Enter first number">
<select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" name="num2" placeholder="Enter second number">
<input type="submit" name="submit" value="Calculate">
</form>
<?php
if(isset($_POST['submit'])){
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$operator = $_POST['operator'];
switch ($operator) {
case '+':
$result = $num1 + $num2;
break;
case '-':
$result = $num1 - $num2;
break;
case '*':
$result = $num1 * $num2;
break;
case '/':
$result = $num1 / $num2;
break;
default:
$result = 0;
break;
}
echo "<br>Result: " . $result;
}
?>
</body>
</html>
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!