PhpSnip.com

User Stats

Simple Calculator Example

A simple Add, Subtract, Multiply, and Divide Calculator. This is a short example of a form, data validation, commenting, CSS, HTML, and rather neat code. Beginners may benifit from the source code contained within.

Info

 Download  View Source (print view)
 Rating : 4.7  Views : 490

Source Code ( 97 lines )

<?
	/*
	Calculator - by Jason Garber
	www.ionzoft.com
	
	This is a short example of a form, data validation, commenting, and rather neat code.
	
	Started Coding at 9:09
	Finished testing and debugging at 9:35
	24 Minutes
	*/

	//Get the double values of the inputs (convert them from string to double)
	$txtNUMER = doubleval($txtNUMER);
	$txtDENOM = doubleval($txtDENOM);
	
	//If the ACTION is SOLVE
	//Note: Action is an hidden input tag.  It will NOT be present the first time the page is loaded
	if($ACTION == "SOLVE")
	{
		//What operator are we using?
		switch($cboOPER)
		{
			case 'ADD':
				$sOut = "$txtNUMER + $txtDENOM = " . ($txtNUMER + $txtDENOM);
			break;

			case 'SUB':
				$sOut = "$txtNUMER - $txtDENOM = " . ($txtNUMER - $txtDENOM);			
			break;
	
			case 'MUL':
				$sOut = "$txtNUMER * $txtDENOM = " . ($txtNUMER * $txtDENOM);			
			break;
	
			case 'DIV':
				if($txtDENOM == 0)	//Check for divide by 0 condition
					$sOut = "Error: Divide by Zero";
				else
					$sOut = "$txtNUMER / $txtDENOM = " . ($txtNUMER / $txtDENOM);			
			break;
	
			default:	//If we are here, then someone was probably monkeying with the query string...
				$sOut = "Error: Invalid Operator";
		}			
	}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
	<title>Calculator</title>
	<style type="text/css">
		body
		{
			font-family: Tahoma;
			font-size: smaller;
		}
	
	</style>
</head>

<body>
	<h1>Calculator</h1>
	<h3 style="color: navy;">Enter your Calculation and click Solve:</h3>
	<br>
	<h4 style="color: red;"><?= $sOut?></h4>
	<form name="frmCalc" action="<?= $PHP_SELF?>" method="get">
		<input type="Hidden" name="ACTION" value="SOLVE">
		<table>
			<tr>
				<td></td>
				<td><input type="Text" name="txtNUMER" width="12" value="<?= $txtNUMER ?>"></td>
			</tr>
			<tr>
				<td>
					<select name="cboOPER" size="1">
						<option value="ADD" <?= ($cboOPER == "ADD" ? "selected" : "")?>>+</option>
						<option value="SUB" <?= ($cboOPER == "SUB" ? "selected" : "")?>>-</option>
						<option value="MUL" <?= ($cboOPER == "MUL" ? "selected" : "")?>>*</option>					
						<option value="DIV" <?= ($cboOPER == "DIV" ? "selected" : "")?>>/</option>
					</select>
				</td>
				<td><input type="Text" name="txtDENOM" width="12" value="<?= $txtDENOM ?>"></td>		
			</tr>
			<tr>
				<td colspan="2"><hr width="100%"></td>
			</tr>
			<tr>
				<td></td>
				<td align="right"><input type="Submit" value="Solve"></td>
			</tr>
		</table>
	</form>
</body>
</html>

Search

Subscribe

  Rss Feeds

Sponsors

Advertise