S
875
Just wanna share to you the code for a simple PHP calculator, hope it helps especially those who are learning PHP.
PHP:
<?php
if(isset($_POST['calc']) && $_POST['calc'] == "Calculate")
{
$_POST['int1']=trim((int)$_POST['int1']);
$_POST['int2']=trim((int)$_POST['int2']);
$_POST['math']=$_POST['math'];
$int1=$_POST['int1'];
$int2=$_POST['int2'];
$math=$_POST['math'];
if(!empty($math) && $math == 1)
{
$math="+";
$tot=$int1+$int2;
}
elseif(!empty($math) && $math == 2)
{
$math="-";
$tot=$int1-$int2;
}
elseif(!empty($math) && $math == 3)
{
$math="/";
$tot=$int1/$int2;
}
elseif(!empty($math) && $math == 4)
{
$math="*";
$tot=($int1*$int2);
}
print "$int1 $math $int2 = $tot";
exit;
}
else
{
//this is html embedded inside PHP
print "<form action='".$_SERVER['PHP_SELF']."' method='post'>
number 1:<input type='text' name='int1' /><br/>
number 2:<input type='text' name='int2' /><br/>
Math Symbol:<select name='math'>
<option value='1'>Add</option>
<option value='2'>Subtract</option>
<option value='3'>Divide</option>
<option value='4'>Multiply</option>
</select><br/>
<input type='submit' name='calc' value='Calculate' />
</form>";
}
?>