What's new

Help Calculator Code

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.
 

Similar threads

Back
Top