Infolinks

Breaking

Adsense

Friday, January 22, 2016

CALCULATOR IN PHP: Create A Simple Calculator

Hi there! The following tutorial will introduce you to one of the most common problems encountered in programming subjects. Later on, I will provide set of activities and quizzes for you to practice on to improve your programming skills.

A simple calculator is just one of the exercises given by most programming instructors. Some other exercises are the following:
  1. Celsius to Fahrenheit Temperature Converter
  2. Identify if odd or even number
  3. Display numbers using a for loop
  4. Solve for the area of a triangle
  5. Fibonacci Series
and many more. These are just some of the activities that I posted here in my blog. You can visit the links if you want.

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! ^_^

CALCULATOR IN PHP: Create A Simple Calculator

No comments:

Post a Comment

Adbox