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

COMPARISION OF TWO NUMBER – PHP

<!DOCTYPE html>
<html lang=”en-US”>
<head>
<meta charset=”UTF-8″>
<title>PHP</title>
</head>
<body>
<?php
$a=10;
$b=5;
if($a==$b)
{
echo “Both are equal”;
}
if($a<$b)
{
echo “B is greater than A”;
}
else
{
echo “A is greater than B”;
}
?>
</body>
</html>