Skip to content

Instantly share code, notes, and snippets.

@pchatterjee
Created September 30, 2019 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pchatterjee/6ebbb445c2f595460c10fffc7747d470 to your computer and use it in GitHub Desktop.
Save pchatterjee/6ebbb445c2f595460c10fffc7747d470 to your computer and use it in GitHub Desktop.
<?php
/* ======================================================
PHP Calculator example using "sticky" form (Version 2)
======================================================
Author : P Chatterjee
Purpose : Simple example using a function.
input:
x, y : numbers
op= operation
calc : Calculate button (client side)
calc : PHP function (server side)
*/
// grab the form values from $_HTTP_POST_VARS hash
extract($_GET);
// first compute the output, but only if data has been input
if(isset($calc)) { // $calc exists as a variable
$prod = calc($x, $y, $op);
}
else { // set defaults
$x=0;
$y=0;
$prod=0;
}
?>
<html>
<head>
<title>PHP Calculator Example</title>
</head>
<body>
<h3>PHP Calculator (using function)</h3>
<p>Basic Arithmetic Calculator</p>
<!-- print the result -->
<form method="get" action="<?php print $_SERVER['PHP_SELF']; ?>">
x = <input type="text" name="x" size="5" value="<?php print $x; ?>"/>
<select name="op" size="1">
<option value="+" <?php if (isset($op) AND $op=="+")
echo 'selected = "selected"' ?>>+</option>
<option value="-" <?php if (isset($op) AND $op=="-")
echo 'selected = "selected"' ?>>-</option>
<option value="*" <?php if (isset($op) AND $op=="*")
echo 'selected = "selected"' ?>>*</option>
<option value="/" <?php if (isset($op) AND $op=="/")
echo 'selected = "selected"' ?>>/</option>
</select>
y = <input type="text" name="y" size="5" value="<?php print $y; ?>"/>
<input type="submit" name="calc" value="Calculate"/>
</form>
<!-- print the result -->
<?php if(isset($calc)) {
print "<p>$x $op $y = $prod</p>";
} ?>
</body>
</html>
<?php
function calc($x, $y, $op) {
switch ($op) { // calculate result based on operator selected
case "+":
$prod = $x + $y;
break;
case "-":
$prod = $x - $y;
break;
case "*":
$prod = $x * $y;
break;
case "/":
if ($y==0) {
$prod = '&infin;';
} else {
$prod = $x / $y;
}
break;
}
return $prod;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment