## Performing Arithmetic

Just as you learned in grade school, basic mathematics involves the principles of addition, subtraction, multiplication, and division. These are performed in PHP using the most obvious operators:

Addition (

)**+**Subtraction (

)**-**Multiplication (

)*****Division (

)**/**

To use these operators, you’ll create a PHP script that calculates the total cost for the sale of some widgets. This handling script could be the basis of a shopping cart application—a very practical web page feature (although in this case the relevant number values will come from ` calculator.html`).

When you’re writing this script, be sure to note the comments (**Script 4.2**) used to illuminate the different lines of code and the reasoning behind them.

**Script 4.2** This PHP script performs all the standard mathematical calculations using the numbers submitted from the form.

1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <title>Product Cost Calculator</ title> 6 <style type="text/css"> 7 .number { font-weight: bold; } 8 </style> 9 </head> 10 <body> 11 <?php // Script 4.2 - handle_calc.php 12 /* This script takes values from calculator.html and performs 13 total cost and monthly payment calculations. */ 14 15 // Address error handling, if you want. 16 17 // Get the values from the $_POST array: 18$price = $_POST['price'];19$quantity = $_POST['quantity'];20$discount = $_POST['discount'];21$tax = $_POST['tax'];22$shipping = $_POST['shipping'];23$payments = $_POST['payments'];24 25 // Calculate the total: 26$total = $price * $quantity;27$total = $total + $shipping;28$total = $total - $discount;29 30 // Determine the tax rate: 31$taxrate = $tax / 100;32$taxrate = $taxrate + 1;33 34 // Factor in the tax rate: 35$total = $total * $taxrate;36 37 // Calculate the monthly payments: 38$monthly = $total / $payments;39 40 // Print out the results: 41print "<p>You have selected topurchase:<br>42<span class=\"number\">$quantity</span> widget(s) at <br>43$<span class=\"number\">$price</span>price each plus a <br>44$<span class=\"number\">$shipping</span> shipping cost and a <br>45<span class=\"number\">$tax</span>percent tax rate.<br>46After your $<spanclass=\"number\">$discount</span>discount, the total cost is47$<span class=\"number\">$total</span>.<br>48Divided over <spanclass=\"number\">$payments</span>monthly payments, that would be$<span class=\"number\">$monthly</span> each.</p>";49 50 ?> 51 </body> 52 </html>

**To create your sales cost calculator:**

Create a new document in your text editor or IDE, to be named

(Script 4.2):**handle_calc.php****<!doctype html>****<html lang="en">****<head>****<meta charset="utf-8">****<title>Product Cost Calculator</title>****<style type="text/css">****.number {font-weight:bold;}****</style>****</head>****<body>**The head of the document defines one CSS class, named

. Any element within the page that has that class value will be given extra font weight. In other words, when the numbers from the form, and the results of the various calculations, are printed in the script’s output, they’ll be made more obvious.`number`Insert the PHP tag and address error handling, if desired:

**<?php // Script 4.2 - handle_calc.php**Depending on your PHP configuration, you may or may not want to add a couple of lines that turn on

and adjust the level of error reporting. See Chapter 3 for specifics.**display_errors**(However, as also mentioned in that chapter, it’s best to make these adjustments in PHP’s primary configuration file.)

Assign the

elements to local variables:**$_POST****$price = $_POST['price'];****$quantity = $_POST['quantity'];****$discount = $_POST['discount'];****$tax = $_POST['tax'];****$shipping = $_POST['shipping'];****$payments = $_POST['payments'];**The script will receive all the form data in the predefined

variable. To access individual form values, refer to**$_POST****$_POST['**`index`, replacing**']**with the corresponding form element’s`index`value. These values are assigned to individual local variables here, to make it easier to use them throughout the rest of the script.**name**Note that each variable is given a descriptive name and is written entirely in lowercase letters.

Begin calculating the total cost:

**$total = $price * $quantity;****$total = $total + $shipping;****$total = $total - $discount;**The asterisk (

) indicates multiplication in PHP, so the total is first calculated as the number of items purchased (*****) multiplied by the price. Then the shipping cost is added to the total value (remember that the shipping cost correlates to the**$quantity**attribute of each shipping drop-down menu’s**value**tags), and the discount is subtracted.**option**Note that it’s perfectly acceptable to determine a variable’s value in part by using that variable’s existing value (as is done in the last two lines).

Calculate the tax rate and the new total:

**$taxrate = $tax / 100;****$taxrate = $taxrate + 1;****$total = $total * $taxrate;**The tax rate should be entered as a percent—for example, 8 or 5.75. This number is then divided by 100 to get the decimal equivalent of the percent (.08 or .0575). Finally, you calculate how much something costs with tax by adding 1 to the percent and then multiplying that new rate by the total. This is the mathematical equivalent of multiplying the decimal tax rate times the total and then adding this result to the total (for example, a 5 percent tax on $100 is $5, making the total $105, which is the same as multiplying $100 times 1.05).

Calculate the monthly payment:

**$monthly = $total / $payments;**As an example of division, assume that the widgets can be paid for over the course of many months. Hence, you divide the total by the number of payments to find the monthly payment.

Print the results:

**print "<p>You have selected to purchase:<br>****<span class=\"number\">$quantity</span> widget(s) at <br>****$<span class=\"number\">$price</span> price each plus a <br>****$<span class=\"number\">$shipping</span> shipping cost and a <br>****<span class=\"number\">$tax</span> percent tax rate.<br>****After your $<span class=\"number\">$discount</span> discount, the total cost is****$<span class=\"number\">$total</span>.<br>****Divided over <span class=\"number\">$payments</span> monthly payments, that would be $<span class=\"number\">$monthly</span> each.</p>";**The

statement sends every value to the browser along with some text. To make it easier to read,**print**tags are added to format the browser result; in addition, the**<br>**function operates over multiple lines to make the PHP code cleaner. Each variable’s value will be highlighted in the browser by wrapping it within span tags that have a**print**attribute of**class**(see Step 1).`number`Close the PHP section, and complete the HTML page:

**?>****</body>****</html>**Save the script as

, and place it in the proper directory for your PHP-enabled server.**handle_calc.php**Make sure that

is in the same directory.**calculator.html**Test the script in your browser by filling out and submitting the form.

Not to belabor the point, but make sure you start by loading the HTML form through a URL (

*http://something*) so that when it’s submitted, the PHP script is also run through a URL.You can experiment with these values to see how effectively your calculator works. If you omit any values, the resulting message will just be a little odd but the calculations should still work .