Operator Precedence


Now that we've got all these new operators floating around+, -, ++, %, and so ona new question arises: if you use a bunch of these operators at the same time, which comes first? For example, what's the result of the following script?

 <?php     echo 4 + 2 * 9; ?>  

Will the + part be evaluated first, giving 4 + 2 * 9 = 6 * 9 = 54, or will the * part be evaluated first, giving 4 + 2 * 9 = 4 + 18 = 22?

The answer is 22 because the * operator has precedence over the + operator when you mix them up like this. You can see the complete list of PHP operator precedence in Table 2-1. The operators with the highest precedence are at the top, and the lowest are at the bottom. As you can see in the table, the * operator is above the + operator.

If operator precedence is interfering with your goal, you can always clarify how you want items to be evaluated by using parentheses. For example, you'll get 22 when you run this script:

 <?php     echo 4 + 2 * 9; ?>  

But you can use parentheses to tell PHP what to do. If you change this expression to (4 + 2) * 9, then you'll get 6 * 9 = 54. Take a look at phpprecedence.php in Example 2-3 to see this at work.

Example 2-3. Incrementing and Decrementing, phpprecedence.php
 <HTML>     <HEAD><TITLE>Setting operator precedence</TITLE></HEAD>     <BODY>         <H1>Setting operator precedence</H1> <?php     echo "4 + 2 * 9 = ", 4 + 2 * 9, "<BR>";     echo "(4 + 2) * 9", (4 + 2) * 9, "<BR>";     echo "4 + (2 * 9)", 4 + (2 * 9), "<BR>"; ?>     </BODY> </HTML> 

The results, where we've set our own execution precedence, appear in Figure 2-3.

Figure 2-3. Setting execution precedence.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

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