Using Number Variables in PHP
Chapter 2, “Variables,” loosely discussed the different types of variables, how to assign values to them, and how they’re generally used. In this chapter, you’ll work specifically with number variables—both integers (whole numbers) and floating-point numbers (aka floats or decimals).
The chapter begins by creating an HTML form that will be used to generate number variables. Then you’ll learn how to perform basic arithmetic, how to format numbers, and how to cope with operator precedence. The last two sections of this chapter cover incrementing and decrementing numbers and generating random numbers. Throughout the chapter, you’ll also find mentions of other useful number-related PHP functions.
Creating the Form
Most of the PHP examples in this chapter will perform various calculations based on an e-commerce premise. A form will take quantity, price, tax rate, shipping cost, and discount values, and the PHP script that handles the form will return a total cost. That cost will also be broken down by the number of payments the user wants to make in order to generate a monthly cost value.
To start, let’s create an HTML page that allows the user to enter the different values (Figure 4.1).
Figure 4.1 This form takes numbers from the user and sends them to the PHP page.
To create the HTML form:
Begin a new HTML document in your text editor or IDE (Script 4.1):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Product Cost Calculator </title> </head> <body><!-- Script 4.1 - calculator.html --> <div><p>Fill out this form to calculate the total cost:</p>
Script 4.1. This basic HTML form generates the numbers upon which mathematical calculations will be performed in a PHP script.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 2 "http://www.w3.org/TR/xhtml1/DTD/ xhtml1-transitional.dtd"> 3 <html xmlns="http://www.w3.org/1999/ xhtml" xml:lang="en" lang="en"> 4 <head> 5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 6 <title>Product Cost Calculator</title> 7 </head> 8 <body><!-- Script 4.1 - calculator.html --> 9 <div><p>Fill out this form to calculate the total cost:</p> 10 11 <form action="handle_calc.php" method="post"> 12 13 <p>Price: <input type="text" name="price" size="5" /></p> 14 15 <p>Quantity: <input type="text" name="quantity" size="5" /></p> 16 17 <p>Discount: <input type="text" name="discount" size="5" /></p> 18 19 <p>Tax: <input type="text" name="tax" size="3" /> (%)</p> 20 21 <p>Shipping method: <select name="shipping"> 22 <option value="5.00">Slow and steady </option> 23 <option value="8.95">Put a move on it. </option> 24 <option value="19.36">I need it yesterday!</option> 25 </select></p> 26 27 <p>Number of payments to make: <input type="text" name="payments" size="3" /></p> 28 29 <input type="submit" name="submit" value="Calculate!" /> 30 31 </form> 32 33 </div> 34 </body> 35 </html>
Create the initial form tag:
<form action="handle_calc.php" method="post">
This form tag begins the HTML form. Its action attribute indicates that the form data will be submitted to a page called handle_calc.php. The tag’s method attribute tells the page to use POST to send the data. See Chapter 3, “HTML Forms and PHP,” for more on any of this.
Create the inputs for the price, quantity, discount, and tax:
<p>Price: <input type="text" name="price" size="5" /></p> <p>Quantity: <input type="text" name="quantity" size="5" /></p> <p>Discount: <input type="text" name="discount" size="5" /></p> <p>Tax: <input type="text" name="tax" size="3" /> (%)</p>
HTML has no input type for numbers, so you create text boxes for these values. A parenthetical indicates the formatting for the tax as a percent.
Also remember that the names used for the inputs have to correspond to valid PHP variable names (letters, numbers, and the underscore only; doesn’t start with a number, and so forth).
Add a field in which the user can select a shipping method:
<p>Shipping method: <select name="shipping"> <option value="5.00">Slow and steady</option> <option value="8.95">Put a move on it.</option> <option value="19.36">I need it yesterday!</option> </select></p>
The shipping selection is done using a drop-down menu. The value of the selected option is the cost for that option. Therefore, if the user selects, for example, the Put a move on it. option, the value of $_POST['shipping'] in handle_calc.php will be 8.95.
Complete the HTML form:
<p>Number of payments to make: <input type="text" name="payments" size="3" /></p> <input type="submit" name="submit" value="Calculate!" /> </form>
The final two input types take a number for how many payments are required and then create a submit button (labeled Calculate!). The closing form tag marks the end of the form section of the page.
Complete the HTML page:
</div> </body> </html>
Save the script as calculator.html and view it in your Web browser.
Because this is an HTML page, you can view it directly in a Web browser.
Script 4.2. This PHP script performs all the standard mathematical calculations using the numbers submitted from the form.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 2 "http://www.w3.org/TR/xhtml1/DTD/ xhtml1-transitional.dtd"> 3 <html xmlns="http://www.w3.org/1999/ xhtml" xml:lang="en" lang="en"> 4 <head> 5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 6 <title>Product Cost Calculator</title> 7 <style type="text/css" media="screen"> 8 .number { font-weight: bold;} 9 </style> 10 </head> 11 <body> 12 <?php // Script 4.2 - handle_calc.php 13 /* This script takes values from calculator.html and performs 14 total cost and monthly payment calculations. */ 15 16 // Address error handling, if you want. 17 18 // Get the values from the $_POST array: 19 $price = $_POST['price']; 20 $quantity = $_POST['quantity']; 21 $discount = $_POST['discount']; 22 $tax = $_POST['tax']; 23 $shipping = $_POST['shipping']; 24 $payments = $_POST['payments']; 25 26 // Calculate the total: 27 $total = $price * $quantity; 28 $total = $total + $shipping; 29 $total = $total - $discount; 30 31 // Determine the tax rate: 32 $taxrate = $tax/100; 33 $taxrate = $taxrate + 1; 34 35 // Factor in the tax rate: 36 $total = $total * $taxrate; 37 38 // Calculate the monthly payments: 39 $monthly = $total / $payments; 40 41 // Print out the results: 42 print "<div>You have selected to purchase:<br /> 43 <span class=\"number\">$quantity</span> widget(s) at <br /> 44 $<span class=\"number\">$price</span> price each plus a <br /> 45 $<span class=\"number\">$shipping</span> shipping cost and a <br /> 46 <span class=\"number\">$tax</span> percent tax rate.<br /> 47 After your $<span class=\"number\"> $discount</span> discount, the total cost is 48 $<span class=\"number\">$total </span>.<br /> 49 Divided over <span class=\"number\"> $payments</span> monthly payments, that would be $<span class=\"number\">$monthly </span> each.</p></div>"; 50 51 ?> 52 </body> 53 </html>