PHP - How To Make a Simple Calculator with PHP - Just a test blog
That's all folks!

If you don't have any knowledge of PHP, I urge you to read my PHP - Introduction and How To Set Up a Local Server To Test PHP Scripts first and then get on with this tutorial.

To make a calculator, you need to make a process.php file along with your index.php:


Then, create a form in your 'index.php' with an action event pointing to your 'process.php' file and in the form create 4 text inputs and a submit button:

<form action="process.php" method="post">

Add <br/>
<input name="num1" type="text"><br/>+<br/>
<input name="num2" type="text"><br/>
<input type="submit"><br/><br/>
Subtract <br/>
<input name="num3" type="text"><br/>-<br/>
<input name="num4" type="text"><br/>
<input type="submit">

</form>

Now open your 'process.php' and follow/copy the code below:

<?php

$num1 = $_POST["num1"];
$num2 = $_POST["num2"];
$sum = $num1 + $num2;
echo "Add equal: " . "$sum". "<br/>";

$num3 = $_POST["num3"];
$num4 = $_POST["num4"];
$sum1 = $num3 - $num4;
echo "Subtract equal: " . "$sum1";

?>

What's happening in the code above is that num1-num4 variables are fetching whatever is being put in the inputs of the form in index.php with help of a special variable '$_POST' and with a simple $sum, 'num1-num4' values are being added and subtracted and send out to the screen with 'echo' commands.

I may not have described this the best way but that's basically what's happening in that code.

Now if you are clever enough (which I'm not) you can use this 'fetching' and 'calculating' PHP code to do alot more than what I've shown here.

If you want to get my version of index.php (as shown in the image) click Here.

If you have any questions or anything, Please let us know down below.

SHARE ON:

FACEBOOK TWITTER GOOGLE+