A simple calculator is just one of the exercises given by most programming instructors. Some other exercises are the following:
- Celsius to Fahrenheit Temperature Converter
- Identify if odd or even number
- Display numbers using a for loop
- Solve for the area of a triangle
- Fibonacci Series
This example is just a simple PHP script to calculate two (2) values based on the selected operator. The sample output is posted below for illustration. We will be using conditional if statements, variables, arithmetic operators and comparison operators.
Output
HTML and PHP Code Simple Calculator
<form method="post">
<input type="number" name="first">
<select name="operator">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type="number" name="second">
<input type="submit" name="calc" value="Calculate">
</form>
<?php
if(isset($_POST['calc']))
{
$first=$_POST['first'];
$second=$_POST['second'];
$op=$_POST['operator'];
if($op=="+")
$answer=$first+$second;
if($op=="-")
$answer=$first-$second;
if($op=="*")
$answer=$first*$second;
if($op=="/")
$answer=$first/$second;
echo $answer;
}
?>
First thing to do is create your HTML code which contains two textboxes, a combo box/dropdown box and a submit button. Since we will be perform arithmetic operators on two numbers, we will be needing to textboxes to gather inputs from the user.
In the php code above, we need to used a conditional statement to compare selected operator from a dropdown box to be able to perform certain operation such as addition, subtraction, multiplication and division. In every condition, you need to create a formula to be executed once the above condition is true.
Hope you can create your own simple calculator in php. Hope this helps! Good day! ^_^
No comments:
Post a Comment