Using Multiple Operators

I l @ ve RuBoard

Inevitably, after discussing the different sorts of mathematical operators, one comes to the discussion of precedence. Precedence refers to the order in which a series of calculations will be executed. For example, what will be the value of the following variable?

 $Number = 10  4 / 2; 

Will $Number be worth 3 (10 minus 4 equals 6 divided by 2 equals 3) or 8 (4 divided by 2 equals 2 subtracted from 10 equals 8)? The answer here is 8, because division takes precedence over subtraction. Appendix C: PHP Resources shows the complete list of operator precedence for PHP (including those we haven't covered yet).

However, instead of attempting to memorize a large table of peculiar characters , my recommendation would be to bypass the whole concept by using parentheses. Parentheses always take precedence over any other operator. Thus:

 $Number = (10  4) / 2; $Number = 10  (4 / 2); 

In the first example, $Number is now equal to 3, and in the second example, $Number is equal to 8. Using parentheses in your calculations will insure that you never obtain peculiar results from them because of precedence.

You can rewrite your script, combining multiple lines into one while still maintaining accuracy by using parentheses.

To use parentheses to establish precedence:

  1. Open numbers .php in your text editor (Script 4.3).

  2. Change line 13 to read (Script 4.4):

     $TotalCost = (($Cost * $Quantity) -   $Discount) * $Tax; 

    There is no reason not to make all of the calculations in one step, as long as you use parentheses to insure that the math works out properly. The other option is to memorize PHP's rules of precedence for multiple operators, but using parentheses is a lot easier.

    Script 4.4. Instead of performing the calculations over several lines, you've trimmed it down to one, without affecting its mathematical basis. With parentheses, you do not need to concern yourself with precedence.

    graphics/04sc04.jpg

  3. Delete lines 10 and 12.

    Since all of the calculations are being made on one line, these other two lines are no longer necessary.

  4. Save your script, upload it to the server, and test it in your browser (Figure 4.5).

    Figure 4.5. Even though the calculations have been condensed, the math should still work out the same. If you see different results here or if you get an error message, double-check your parentheses.

    graphics/04fig05.gif

Tip

Watch that you match your parentheses consistently as you create your formulas (every opening parentheses requires a closing parentheses).


I l @ ve RuBoard


PHP for the World Wide Web (Visual QuickStart Guide)
PHP for the World Wide Web (Visual QuickStart Guide)
ISBN: 0201727870
EAN: 2147483647
Year: 2001
Pages: 116
Authors: Larry Ullman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net