How can PHP be used to perform basic arithmetic operations based on user input from a form?
To perform basic arithmetic operations based on user input from a form using PHP, you can create a form with input fields for the numbers to be calculated and a select dropdown for the operation to be performed. When the form is submitted, you can use PHP to retrieve the input values, perform the selected operation, and display the result to the user.
<?php
if(isset($_POST['submit'])) {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$operation = $_POST['operation'];
switch($operation) {
case 'add':
$result = $num1 + $num2;
break;
case 'subtract':
$result = $num1 - $num2;
break;
case 'multiply':
$result = $num1 * $num2;
break;
case 'divide':
$result = $num1 / $num2;
break;
default:
$result = "Invalid operation";
}
echo "Result: $result";
}
?>
<form method="post">
<input type="text" name="num1" placeholder="Enter first number">
<select name="operation">
<option value="add">+</option>
<option value="subtract">-</option>
<option value="multiply">*</option>
<option value="divide">/</option>
</select>
<input type="text" name="num2" placeholder="Enter second number">
<input type="submit" name="submit" value="Calculate">
</form>