How to Create a Simple Calculator in PHP

 
previously shared my complete PHP video series with you and now I’m going to share a simple online calculator with you which is created using PHP without MySQL. Because you can create any simple application in PHP by simply using IF statements. So I’ve done the same in this tutorial. However, My aim is to provide you a large number of tutorials in which we’ll be making small applications and projects such as online currency converter, visitors counter, love calculator, Luck Calculator and many more. I’ll be providing you video tutorials and the source code which we’d have used during the video tutorials. For now let’s create a simple calculator application in PHP. There will be 2 video tutorials which will practically teach you doing this and source code is also available for you to practice on.

Creating a simple calculator in PHP

Let’s assume, we want to create a simple calculator and without using MySQL. So yes, it is possible only by using IF statement in PHP. First you need to create a new file for writing the codes, and you can use Notepad or notepad++ for this purpose, though, I’ve used Notepad++ in these video tutorials. Just save the file and name it as calculator.php; save the file in the htdocsfolder of your XAMPP Installation, because that is our root folder and we run files from that folder on our local server (Localhost). Now for creating a calculator you need to first create a form in HTML and add some input tags.
Here is the HTML code for the calculator, and we’ll later on add PHP code to this:
<html>
<head>
<title>Simple PHP Calculator</title>
</head>
<body>
<form method=’post’ action=’calculator.php’>
<input type=’text’ name=’value1′>
<input type=’text’ name=’value2′>
<select name=’action’>
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type=’submit’ name=’submit’ value=’Calcaulate Now’>
</form>
</body>
</html>
And after creating the HTML form we need to start work in PHP so that this project will be completed, watch below video for practically learn about creating a PHP script for this calculator.

I hope you’ve understood creating it the PHP script easily for this simple calculator, however, the source code is being shared here, just copy it and paste it inside that file in which we already created an HTML form:
<?php
if(isset($_POST[‘submit’])){
$value1 = $_POST[‘value1’];
$value2 = $_POST[‘value2’];
$action = $_POST[‘action’];
if($action==”+”){
echo “<b>Your Answer is:</b><br>”;
echo $value1+$value2;
}
if($action==”-“){
echo “<b>Your Answer is:</b><br>”;
echo $value1-$value2;
}
if($action==”*”){
echo “<b>Your Answer is:</b><br>”;
echo $value1*$value2;
}
if($action==”/”){
echo “<b>Your Answer is:</b><br>”;
echo $value1/$value2;
}
}
?>
Now check your online calculator in your browser, and remember, always open your PHP files using this address: localhost. Sometimes mistakenly you directly click on the file which is inside a folder.