# Create Basic Calculator in PHP

by Sam

One of the most common exercises we encounter in computer programming is basic calculator. That’s why, I posted this exercise for PHP beginners.

Below are the functionalities about the source code:

• Display the result of first and second number based on the operation submitted.
• Check if first and second numbers are not empty.
• In division, it is invalid to directly divide a number by Zero. Hence, we need to validate it first and display an error message if the divisor is zero.

``````
<!DOCTYPE html>
<html>
<title>Basic Calculator</title>
<body>
<?php
if( isset(\$_POST['fnum']) && isset(\$_POST['snum']) )
{
\$fnum = \$_POST['fnum']
\$snum = \$_POST['snum'];
//validation
if( \$fnum != "" && \$snum != "")
{
echo "The Sum is : " . (\$fnum + \$snum);
}elseif( isset(\$_POST['subtract']) ){
echo "The Difference is : " . (\$fnum - \$snum);
}elseif( isset(\$_POST['multiply']) ){
echo "The Product is : " . (\$fnum * \$snum);
}elseif( isset(\$_POST['divide']) ){
if( \$snum == 0)
echo "Error: Cannot divide by Zero";
else
echo "The Quotient is : " . (\$fnum / \$snum);
}
}
}
?>
<h2>Basic Calculator</h2>
<form action="" method="POST">
<table>
<tr>
<td>Enter First number : </td>
<td><input type="text" name="fnum"></td>
</tr>
<tr>
<td>Enter Second number : </td>
<td><input type="text" name="snum"></td>
</tr>
</table>
<input type="submit" name="subtract" value="Subtract">&nbsp;
<input type="submit" name="multiply" value="Multiply">&nbsp;
<input type="submit" name="divide" value="Divide">
</form>
</body>
</html>
``````

If you have questions, feel free to comment below.

# Need of a Website?

Maybe you're planning to build a landing page for your website. You might also have a plan to create a web application. I can offer you with an affordable but with good quality services. Don't hesitate to submit your specifications by clicking the button below.

Get Quote