- Before You Begin: Accessing PHP
- Creating a Sample Application: Bob's Auto Parts
- Embedding PHP in HTML
- Adding Dynamic Content
- Accessing Form Variables
- Understanding Identifiers
- Examining Variable Types
- Declaring and Using Constants
- Understanding Variable Scope
- Using Operators
- Working Out the Form Totals
- Understanding Precedence and Associativity
- Using Variable Handling Functions
- Making Decisions with Conditionals
- Repeating Actions Through Iteration
- Breaking Out of a Control Structure or Script
- Employing Alternative Control Structure Syntax
- Using declare
- Next
Working Out the Form Totals
Now that you know how to use PHP’s operators, you are ready to work out the totals and tax on Bob’s order form. To do this, add the following code to the bottom of your PHP script:
$totalqty = 0;
$totalqty = $tireqty + $oilqty + $sparkqty;
echo "<p>Items ordered: ".$totalqty."<br />";
$totalamount = 0.00;
define('TIREPRICE', 100);
define('OILPRICE', 10);
define('SPARKPRICE', 4);
$totalamount = $tireqty * TIREPRICE
+ $oilqty * OILPRICE
+ $sparkqty * SPARKPRICE;
echo "Subtotal: $".number_format($totalamount,2)."<br />";
$taxrate = 0.10; // local sales tax is 10%
$totalamount = $totalamount * (1 + $taxrate);
echo "Total including tax: $".number_format($totalamount,2)."</p>";
If you refresh the page in your browser window, you should see output similar to Figure 1.5.
Figure 1.5 The totals of the customer’s order have been calculated, formatted, and displayed
As you can see, this piece of code uses several operators. It uses the addition (+) and multiplication (*) operators to work out the amounts and the string concatenation operator (.) to set up the output to the browser.
It also uses the number_format() function to format the totals as strings with two decimal places. This is a function from PHP’s Math library.
If you look closely at the calculations, you might ask why the calculations were performed in the order they were. For example, consider this statement:
$totalamount = $tireqty * TIREPRICE
+ $oilqty * OILPRICE
+ $sparkqty * SPARKPRICE;
The total amount seems to be correct, but why were the multiplications performed before the additions? The answer lies in the precedence of the operators—that is, the order in which they are evaluated.