Home > Articles

  • Print
  • + Share This
This chapter is from the book

Understanding Precedence and Associativity

In general, operators have a set precedence, or order, in which they are evaluated. Operators also have associativity, which is the order in which operators of the same precedence are evaluated. This order is generally left to right (called left for short), right to left (called right for short), or not relevant.

Table 1.7 shows operator precedence and associativity in PHP. In this table, operators with the lowest precedence are at the top, and precedence increases as you go down the table.

Table 1.7 Operator Precedence in PHP

Associativity

Operators

left

,

left

Or

left

Xor

left

And

right

Print

left

= += -= *= /= .= %= &= |= ^= ~= <<= >>=</=>

left

? :

left

||

left

&&

left

|

left

^

left

&

n/a

== != === !==

n/a

< <= >>=</=>

left

<< >></>

left

+ - .

left

* / %

right

!

n/a

Instanceof

right

~ (int) (float) (string) (array) (object) (bool) @

n/a

++ --

right

[]

n/a

clone new

n/a

()

Notice that we haven’t yet covered the operator with the highest precedence: plain old parentheses. The effect of using parentheses is to raise the precedence of whatever is contained within them. This is how you can deliberately manipulate or work around the precedence rules when you need to.

Remember this part of the preceding example:

$totalamount = $totalamount * (1 + $taxrate);

If you had written

$totalamount = $totalamount * 1 + $taxrate;

the multiplication operation, having higher precedence than the addition operation, would be performed first, giving an incorrect result. By using the parentheses, you can force the subexpression 1 + $taxrate to be evaluated first.

You can use as many sets of parentheses as you like in an expression. The innermost set of parentheses is evaluated first.

Also note one other operator in this table we have not yet covered: the print language construct, which is equivalent to echo. Both constructs generate output.

We generally use echo in this book, but you can use print if you find it more readable. Neither print nor echo is really a function, but both can be called as a function with parameters in parentheses. Both can also be treated as an operator: You simply place the string to work with after the keyword echo or print.

Calling print as a function causes it to return a value (1). This capability might be useful if you want to generate output inside a more complex expression but does mean that print is marginally slower than echo.

  • + Share This
  • 🔖 Save To Your Account