-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.php
54 lines (49 loc) · 1.37 KB
/
calculator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];
$operator = $_POST["operator"];
if (empty($num1) || empty($num2)) {
$error = "Please enter both numbers.";
} else if (!is_numeric($num1) || !is_numeric($num2)) {
$error = "Invalid input. Please enter numbers only.";
} else {
$result = "";
switch ($operator) {
case "+":
$result = $num1 + $num2;
break;
case "-":
$result = $num1 - $num2;
break;
case "*":
$result = $num1 * $num2;
break;
case "/":
if ($num2 == 0) {
$error = "Cannot divide by zero.";
} else {
$result = $num1 / $num2;
}
break;
}
}
}
?>
<form method="post">
<?php if (isset($error)) : ?>
<p style="color: red;"><?php echo $error; ?></p>
<?php endif; ?>
<input type="number" name="num1" placeholder="Enter first number">
<select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="number" name="num2" placeholder="Enter second number">
<input type="submit" value="Calculate">
</form>
<?php if (isset($result)) : ?>
<p>The result is: <?php echo $result; ?></p>
<?php endif; ?>