使用表单输入两个数字和操作符,然后使用
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>