 Publishers of technology books, eBooks, and videos for creative people

• Print
This chapter is from the book

## 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:

• 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">
4      <meta charset="utf-8">
5      <title>Product Cost Calculator</
title>
6      <style type="text/css">
7         .number { font-weight: bold; }
8      </style>
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:
41  print "<p>You have selected to
purchase:<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>
class=\"number\">\$discount</span>
discount, the total cost is
47  \$<span class=\"number\">\$total</
span>.<br>
48  Divided over <span
class=\"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:

1. Create a new document in your text editor or IDE, to be named handle_calc.php (Script 4.2):

```<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Product Cost Calculator</title>
<style type="text/css">
.number {font-weight:bold;}
</style>
<body>```

The head of the document defines one CSS class, named number. 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.

2. 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 display_errors and adjust the level of error reporting. See Chapter 3 for specifics.

(However, as also mentioned in that chapter, it’s best to make these adjustments in PHP’s primary configuration file.)

3. Assign the \$_POST elements to local variables:

```\$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 \$_POST variable. To access individual form values, refer to \$_POST['index'], replacing index with the corresponding form element’s name value. These values are assigned to individual local variables here, to make it easier to use them throughout the rest of the script.

Note that each variable is given a descriptive name and is written entirely in lowercase letters.

4. 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 (\$quantity) multiplied by the price. Then the shipping cost is added to the total value (remember that the shipping cost correlates to the value attribute of each shipping drop-down menu’s option tags), and the discount is subtracted.

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).

5. 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).

6. 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.

7. 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 print statement sends every value to the browser along with some text. To make it easier to read, <br> tags are added to format the browser result; in addition, the print 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 class attribute of number (see Step 1).

8. Close the PHP section, and complete the HTML page:

```?>
</body>
</html>```
9. Save the script as handle_calc.php, and place it in the proper directory for your PHP-enabled server.

Make sure that calculator.html is in the same directory.

10. Test the script in your browser by filling out and submitting the form. Click to view larger image The HTML form... Click to view larger image ...and the resulting calculations.

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 . Click to view larger image You can omit or change any value and rerun the calculator. Here the tax and discount values have been omitted.