Step-by-Step Guide: Creating a Calculator Using PHP | Easy PHP Calculator Tutorial
Based on the information you provided, it seems that you are having trouble displaying the answer to a basic PHP calculator on the browser. The main issue in your PHP code is that you are not performing the actual arithmetic operations in your conditions, but instead, you are just concatenating the values and the operators as strings. You also need to put the operator values in quotes when comparing them in the if statements. Here is the corrected version of your PHP code:
<!doctype html>
<html>
<head>
<meta charset=”utf-8″>
<title>Answer</title>
</head>
<body>
<p>The answer is:
<?php
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
$first = $_POST[‘first’];
$second = $_POST[‘second’];
$operator = $_POST[‘group1’];
switch ($operator) {
case ‘add’:
$result = $first + $second;
break;
case ‘subtract’:
$result = $first – $second;
break;
case ‘times’:
$result = $first * $second;
break;
case ‘divide’:
if ($second == 0) {
echo “Cannot divide by zero!”;
return;
}
$result = $first / $second;
break;
default:
echo “Invalid operator!”;
return;
}
echo $result;
}
?>
</p>
</body>
</html>
In this corrected version, I am getting the values of the first
, second
, and group1
variables from the $_POST
superglobal, which will contain the form data submitted by the user. I am then performing the arithmetic operations based on the selected operator using a switch
statement. Note that I am checking if the second value is zero in the divide
case to avoid dividing by zero, which would cause an error. Finally, I am displaying the result by simply outputting it with the echo
statement.
Also, you should change the attribute="post"
attribute in your HTML form to enctype="multipart/form-data"
if you want to support file uploads in the future, although it is not necessary in this case.
I hope this helps! Let me know if you have any further questions.