Calculator in PHP using If-Else Statement
Last Updated :
22 Nov, 2022
PHP (Hypertext Preprocessor) is an open-source & server-side scripting language designed specifically for web development, where the scripts are executed on the server. It is free to download and use & can be easily embedded with HTML files. We can also write HTML codes in a PHP file. PHP calculator is used for performing basic mathematical operations like Addition, subtraction, multiplication, and division. In this article, we will see how to design the Calculator In PHP to perform basic arithmetic operations. For this, we will be using PHP, HTML, & JavaScript.
A simple calculator can be made using a PHP program that is able to add, subtract, multiply and divide, two operands entered by the user. The if-else statement will be used to create a calculator.
Approach: The following approach will be used to create the basic calculator:
We will declare two local variables say num1 and num2 for two numeric values. Then, we will enter the choice(Addition, subtraction, multiplication, or division). Then, it takes two numbers, num1, and num2 for further calculation. With the help of the if-else statement, it will jump to an operator selected by the user. Using the HTML table created the design where variables are holding the input field and the rest of them are filled with input buttons. Now, with the help of function res(), it displays the respective value of the button to the input field every time we click the button. The ans() function is used to set the value pressed from the keyboard to the same input field. All the calculations of the numbers entered can be done by both the "Enter" key and also with the help of the "=" button. The calculate() function will do the calculation with math.evaluate() function and then displays the final result to the input field. The clear_input() function is used whose work is to clear the input field.
Example: This example illustrates the PHP Calculator by implementing the basic if-else statement.
PHP
<!DOCTYPE html>
<html>
<?php
ini_set('resplay_errors',0);
if( isset( $_REQUEST['calculator'] ))
{
$op=$_REQUEST['operator'];
$num1 = $_REQUEST['firstnum'];
$num2 = $_REQUEST['secondnum'];
}
if($op=="+")
{
$res= $num1+$num2;
}
if($op=="-")
{
$res= $num1-$num2;
}
if($op=="*")
{
$res =$num1*$num2;
}
if($op=="/")
{
$res= $num1/$num2;
}
if($_REQUEST['firstnum']==NULL || $_REQUEST['secondnum']==NULL)
{
echo "<script language=javascript> alert(\"Enter values.\");</script>";
}
}
?>
<head>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/mathjs/10.6.4/math.min.js"
integrity=
"sha512-iphNRh6dPbeuPGIrQbCdbBF/qcqadKWLa35YPVfMZMHBSI6PLJh1om2xCTWhpVpmUyb4IvVS9iYnnYMkleVXLA=="
crossorigin="anonymous"
referrerpolicy="no-referrer">
</script>
<style>
table {
border: 1px solid white;
margin-left: auto;
margin-right: auto;
}
input[type="button"] {
width: 88%;
padding: 20px 45px;
background-color: blue;
color: black;
font-size: 25px;
font-weight: bold;
border: none;
border-radius: 5px;
}
input[type="text"] {
padding: 20px 120px;
font-size: 26px;
font-weight: bold;
border: none;
border-radius: 8px;
border: 3px solid black;
}
</style>
</head>
<body>
<table id="calculator">
<tr>
<td colspan="3">
<input type="text" id="answer">
</td>
</tr>
<tr>
<td>
<input type="button"
value="AC"
onclick="clear_input()"
onkeydown="ans(event)">
</td>
<td>
<input type="button"
value="()"
onclick="res('()')"
onkeydown="ans(event)">
</td>
<td>
<input type="button"
value="%"
onclick="res('%')"
onkeydown="ans(event)">
</td>
<td>
<input type="button"
value="/"
onclick="res('/')"
onkeydown="ans(event)">
</td>
</tr>
<tr>
<td>
<input type="button"
value="7"
onclick="res('7')"
onkeydown="ans(event)">
</td>
<td>
<input type="button"
value="8"
onclick="res('8')"
onkeydown="ans(event)">
</td>
<td>
<input type="button"
value="9"
onclick="res('9')"
onkeydown="ans(event)">
</td>
<td>
<input type="button"
value="*"
onclick="res('*')"
onkeydown="ans(event)">
</td>
</tr>
<tr>
<td>
<input type="button"
value="4"
onclick="res('4')"
onkeydown="ans(event)">
</td>
<td>
<input type="button"
value="5"
onclick="res('5')"
onkeydown="ans(event)">
</td>
<td>
<input type="button"
value="6"
onclick="res('6')"
onkeydown="ans(event)">
</td>
<td>
<input type="button"
value="-"
onclick="res('-')"
onkeydown="ans(event)">
</td>
</tr>
<tr>
<td>
<input type="button"
value="1"
onclick="res('1')"
onkeydown="ans(event)">
</td>
<td>
<input type="button"
value="2"
onclick="res('2')"
onkeydown="ans(event)">
</td>
<td>
<input type="button"
value="3"
onclick="res('3')"
onkeydown="ans(event)">
</td>
<td>
<input type="button"
value="+"
onclick="res('+')"
onkeydown="ans(event)">
</td>
</tr>
<tr>
<td>
<input type="button"
value="0"
onclick="res('0')"
onkeydown="ans(event)">
</td>
<td>
<input type="button"
value="."
onclick="res('.')"
onkeydown="ans(event)">
</td>
<td>
<input type="button"
value="clear"
onclick="clearfield()"
onkeydown="ans(event)">
</td>
<!-- calculate function call function calculate to evaluate value -->
<td>
<input type="button"
value="="
onclick="calculate()">
</td>
</tr>
</table>
<script>
function res(val) {
document.getElementById("answer").value += val
}
function clearfield() {
let st = document.getElementById("answer").value
document.getElementById("answer").value =
st.substring(0, st.length - 1);
}
function ans(event) {
if (event.key == '0' || event.key == '1'
|| event.key == '2' || event.key == '3'
|| event.key == '4' || event.key == '5'
|| event.key == '6' || event.key == '7'
|| event.key == '8' || event.key == '9'
|| event.key == '+' || event.key == '-'
|| event.key == '*' || event.key == '/')
document.getElementById("answer").value += event.key;
}
var cal = document.getElementById("calculator");
cal.onkeyup = function (event) {
if (event.keyCode === 13) {
console.log("Enter");
let a = document.getElementById("answer").value
console.log(a);
calculate();
}
}
function calculate() {
let a = document.getElementById("answer").value
let b = math.evaluate(a)
document.getElementById("answer").value = b
}
function clear_input() {
document.getElementById("answer").value = ""
}
</script>
</body>
</html>
Output:
Similar Reads
PHP continue Statement
The continue statement is used within a loop structure to skip the loop iteration and continue execution at the beginning of condition execution. It is mainly used to skip the current iteration and check for the next condition. The continue accepts an optional numeric value that tells how many loops
1 min read
How to check if a String Contains a Substring in PHP ?
Checking whether a string contains a specific substring is a common task in PHP. Whether you're parsing user input, filtering content, or building search functionality, substring checking plays a crucial role.MethodsBelow are the following methods by which we can check if a string contains a substri
1 min read
PHP goto Statement
The goto statement is used to jump to another section of a program. It is sometimes referred to as an unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function. Flowchart of goto statement: Syntax: statement_1; if (expr) goto label; statement_2;
1 min read
How to use a switch case 'or' in PHP?
Problem: How to use a switch case 'or' in PHP? Solution: This can be achieved in 2 ways. They are as follows: Method 1: Without using break keyword in one of the switch case. Example: php <?php $option = 1; switch ($option) { case 1: case 2: echo "The option is either 1 or 2."; break; }
1 min read
PHP to check substring in a string
In this article, we will see how to check the substring in a string. We are given two strings & we have to check whether the second string is a substring of the first string or not using PHP built-in strpos() function. This function is case-sensitive, which means that it treats upper-case and lo
2 min read
How to find the index of an element in an array using PHP ?
In this article, we will discuss how to find the index of an element in an array in PHP. Array indexing starts from 0 to n-1. Here we have some common approachesTable of ContentUsing array_search() FunctionUsing array_flip()Using a custom functionUsing a foreach LoopUsing array_keys FunctionUsing ar
6 min read
PHP switch Statement
The switch statement is similar to the series of if-else statements. The switch statement performs in various cases i.e. it has various cases to which it matches the condition and appropriately executes a particular case block. It first evaluates an expression and then compares it with the values of
2 min read
How to terminate execution of a script in PHP ?
In this article, we are going to discuss how to terminate the execution of a PHP script. In PHP, a coder can terminate the execution of a script by specifying a method/function called the exit() method in a script. Even if the exit() function is called, the shutdown functions and object destructors
2 min read
How to check if a String contains a Specific Character in PHP ?
In PHP, determining whether a string contains a specific character is a common task. Whether you're validating user input, parsing data, or performing text processing, PHP provides several methods to check for the presence of a particular character within a string efficiently. Here are some common a
2 min read
How to do syntax checking using PHP ?
Syntax checking is one of the most important tasks in programming. Our compiler checks our code and shows relevant errors if there is any in the code i.e. compile time, run time, syntax, etc. We can do the same thing i.e. syntax checking in PHP. In this article, we are going to learn how we can do s
2 min read