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