Example 1 – PHP

Simple Calc In PHP

<html>
<head><title>Calc</title></head>
<body>
<h3>Simple Calculator in PHP</h3>
<form action =”#” method=”get”>

<lable>Enter Num 1:</lable>
<input type=”number” name=”num1″ required=”required”><br>
<lable>Enter Num 2:</lable>
<input type=”number” name=”num2″ required=”required”><br>

<table>
<tr>
<td>Add:</td>
<td><input type=”checkbox” name=”check[]” value=”add”></td>
<td>Subtract:</td>
<td><input type=”checkbox” name=”check[]” value=”subtract”></td>
<td>Multiply:</td>
<td><input type=”checkbox” name=”check[]” value=”multiply”></td>
</tr>

<tr>
<td>Division:</td>
<td><input type=”checkbox” name=”check[]” value=”divide”></td>
<td>Modulo:</td>
<td><input type=”checkbox” name=”check[]” value=”mod”></td>
<td>Exponent:</td>
<td><input type=”checkbox” name=”check[]” value=”expo”></td>
</tr>
</table>
<input type=”submit” value=”Calculate” name=”calc”>
</form>

<?php

$n1 = $_GET[‘num1’];
$n2 = $_GET[‘num2’];

if(isset($_GET[‘calc’]))
{

echo “Num 1 is: “.$n1.”<br> Num 2 is: “.$n2;

if (!isset($_GET[‘check’])) {
echo “<br>You haven’t selected any operation”;
exit;
}
else
{
foreach($_GET[‘check’] as $c) {

switch($c)
{
case “add”:
echo “<br><br>Addition is “.($n1+$n2);
break;

case “subtract”:
echo”<br>Subtraction is “.($n1-$n2);
break;

case “multiply”:
echo”<br>MultiplicationĀ  is “.($n1 * $n2);
break;

case “divide”:
echo”<br>Division is “.($n1/$n2);
break;

case “mod”:
echo”<br>Modulus is “.($n1%$n2);
break;

case “expo”:
echo”<br>Exponent is “.($n1 ** $n2); /* This will work only on php 5.6 and + versions*/
break;

default: echo “Can’t calculate”;
break;
}
}
}
}

?>
</body>
</html>

okay, so i have used get method so that you can see which data are passing in URL and in form action you can leave it blank because we are not passing any variable in another php file. Our page has no another page.

This is .PHP file. You can right click on your browser and check view page source.There you can’t see our script. In short php file can handle html tags too!

About the Code:

isset() : it checks weather submit(calculate) button is clicked or not.

again after calculate button clicked there is !isset() function is there is checks if you have not selected any checkbox.

then there is foreach loop it basically cover all our checkbox and help us which one is clicked with the help of switch statement.


Pretty much easier Right? Try to build your own and let us know if you have any trouble !

Advertisements

Author: kanu_lp

Teck Geek guy... Bands Obsessed.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s