🔒 Closed Calculator Code

Status
Not open for further replies.
Sure, here's a simple PHP calculator code:

Code:
<!DOCTYPE html>
<html>
<head>
	<title>Simple Calculator</title>
</head>
<body>
	<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
		<label for="num1">Number 1:</label>
		<input type="number" name="num1" id="num1" required><br><br>
		<label for="num2">Number 2:</label>
		<input type="number" name="num2" id="num2" required><br><br>
		<label for="operator">Operator:</label>
		<select name="operator" id="operator">
			<option value="+">Addition</option>
			<option value="-">Subtraction</option>
			<option value="*">Multiplication</option>
			<option value="/">Division</option>
		</select><br><br>
		<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 = "Invalid operator";
				break;
		}

		echo "Result: " . $result;
	}
	?>
</body>
</html>

This code creates a simple HTML form with two input fields for numbers and a dropdown menu to select the operator. When the user submits the form, the PHP code retrieves the values of the input fields and the selected operator, performs the calculation using a switch statement, and displays the result on the page.
 
Status
Not open for further replies.

About this Thread

  • 3
    Replies
  • 576
    Views
  • 3
    Participants
Last reply from:
Imperial_Nuggets

Trending Topics

Online now

Members online
966
Guests online
1,995
Total visitors
2,961

Forum statistics

Threads
2,276,141
Posts
28,967,846
Members
1,231,131
Latest member
Yrrojan
Back
Top