Calculator App

This project shows you how to create a basic calculator using an HTML form and PHP script. In the HTML form we add a SELECT box to choose the operator (+,-,*,/) for the math problem. Then in the PHP script we use If/Else if?Else statements to determine what the outcome will be. Finally we use a basic validation function to verify the values submitted are actually numbers. If they are we print out the results, and if not we print that one of the values is not a number.

Code Explanation:

For this project there is the math.html HTML form that sends the values to the calc.php PHP script.


Line 1 – We give our app a title

Line 3 – We set the action of the form to send the values to calc.php with a method of post

Line 4 – We create a text box for the first number and name it num1

Lines 5-10 – Create a Select Box with the options for the math operations. value= is what is sent to the php script, the text between the tags is what is displayed for the user

Line 11 – We create the text box for the second number and name it num2

Lines 12-13 – We add a submit button and then close the form

Basic Calculator<br>

<form action="calc.php" method="post">
<input type="text" name="num1">
<select name="action">
    <option value="+">+</option>
    <option value="-">-</option>
    <option value="*">x</option>
    <option value="/">/</option>
<input type="text" name="num2">
<input type="submit">
Code language: HTML, XML (xml)


Line 1 – We open the PHP script

Lines 3-5 – We create the variables for $num1, $num2 and $action and then set them to the values posted from the HTML form

Lines 8-18 – We create If/Else if/Else statement to determine what $num3, the answer, will be.

Lines 20 – 24 – We create an If/Else statement and check to see if $num1 and $num2 are numbers using the is_numeric() function. If they are numbers we print the answer, if not we print that one of the variables is not a number.

Line 25 – We use <br> to create a new line

Line 27 – We print a hyperlink to go back to the HTML form

Line 29 – We close the PHP script


$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$action = $_POST['action'];

if ($action == "+"){
    $num3 = $num1+$num2;
} else if($action == "-"){
    $num3 = $num1-$num2;
} else if ($action == "*"){
    $num3 =$num1*$num2;
} else if($action == "/"){
    $num3 = $num1/$num2;
} else {
    $num3 = "PROBLEM";

if(is_numeric($num1) && is_numeric($num2)){
    echo "$num1 $action $num2 = $num3";
} else {
    echo "$num1, or $num2 is not a number";
echo "<br>";

echo "<a href='math.html'>GO BACK</a>";

Code language: HTML, XML (xml)