Script 13.2 Typecasting variables

Output

Widget Cost Calculator

Source
<?php # Script 13.2 - calculator.php
// This script calculates an order total based upon three form values.

// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

	// Cast all the variables to a specific type:
	$quantity = (int) $_POST['quantity'];
	$price = (float) $_POST['price'];
	$tax = (float) $_POST['tax'];

	// All variables should be positive Tax is optional
	if ( ($quantity > 0) && ($price > 0) && ($tax >= 0) ) {

		// Calculate the total:
		$total = $quantity * $price;
		if($tax>0){
			$total += $total * ($tax/100);
		}
		
		// Print the result:
		echo '<p>The total cost of purchasing ' . $quantity . ' widget';
		echo ($quantity>1)?'s':'';
		echo ' at $' . number_format ($price, 2) . ' each';
		echo ($tax>0)?' with tax':' without tax';
		echo ' is $' . number_format ($total, 2) . '.</p>';
				
	} else { // Invalid submitted values.
		echo '<p style="font-weight: bold; color: #C00">Please enter a valid quantity, price, and tax rate.</p>';
	}	
} ?>
<h2>Widget Cost Calculator</h2>
<form action="" method="post">
	<p>
		<label for="q">Quantity:</label> 
		<input id="q" type="text" name="quantity" size="5" maxlength="10" value="<?php if (isset($quantity)) echo $quantity; ?>" />
	</p>
	<p>
		<label for="p">Price:</label>
		<input id="p" type="text" name="price" size="5" maxlength="10" value="<?php if (isset($price)) echo $price; ?>" />
	</p>
	<p>
		<label for="t">Tax (%):</label> 
		<input id="t" type="text" name="tax" size="5" maxlength="10" value="<?php if (isset($tax)) echo $tax; ?>" />
	</p>
	<p>
		<input type="submit" name="submit" value="Calculate!" />
	</p>
</form>