Showing posts with label Variables. Show all posts
Showing posts with label Variables. Show all posts

Tuesday, October 11, 2011

Simple Calculator in PHP

Code Example

code for calculator.html

<html>
  <head>
    <title>Calculator</title>
  </head>
  <body>
 <form action = "calculator.php">
   <table align="center" cellspacing="20">
  <tr>
   <td>Enter First No.:</td>
   <td><input type="text" name="firstno"></td> 
  </tr>
  <tr>
   <td>Enter Second No.:</td>
   <td><input type="text" name="secondno"></td>
  </tr>
  <tr>
   <td>Select function.</td>
   <td><select name="function">
     <option value="sum">Add</option>
     <option value="sub">Subtract</option>
     <option value="mul">Multiply</option>
     <option value="div">Divide</option>
     </select>
   </td>
  </tr>
  <tr>
   <td colspan="2" align = "center"><input type="submit" value="  Submit  ">  </td>
  </tr>
         </table>
    </form>  
</body>
</html>

code for calculator.php

<html>
<head>
   <title>Calculator</title>
</head>
<body>
 <?php
  $num1=$_GET["firstno"];
  $num2=$_GET["secondno"];
  $function=$_GET["function"];
  switch ($function)
  {
   case 'sum':
    echo $num1+$num2;
    break;
   case 'sub':
    echo $num1-$num2;
    break;
   case 'mul':
    echo $num1*$num2;
    break;
   case 'div':
    echo $num1/$num2;
    break;
   default:
    echo 'Please select a funtion';
  }
 ?>
</body>
</html>


Variables, Data Types and Casting in PHP

Code Example 

<html>
  <body>

<?php
  $num1=25;
  $num2=24;
  echo 'sum of '.$num1.', '.$num2.' : '.($num1+$num2);
   
  $num2=' hello'.$num2;
  echo 'sum of '.$num1.', '.$num2.' : '.($num1+$num2);
  $num3=24;
  $num3=$num3.'hello';
  echo 'sum of '.$num1.' and '.$num3.' : '.($num1+$num3).' note here second data is string ';
?>

  </body>
</html>