# Operator precedence and associativity

When it comes to handling complicated expressions, there is a generally agreed upon set of mathematical rules shared by most programming languages, including PHP, that together are known as operator precedence and associativity. For example, consider the following statement:

``````\$foo = 5 * 10 - 1;
``````

Should \$foo be 49 or 45? If you cannot see why there are two possibilities, it might help to break them up using brackets, like this:

``````\$foo = (5 * 10) - 1
\$foo = 5 * (10 - 1);
``````

In case one, five is multiplied by ten then one is subtracted from the result, but in case two ten has one subtracted from it, making nine, then that result is multiplied by five. If there is any ambiguity in your expressions, PHP will resolve them according to its internal set of rules about operator precedence, that is, which operators are calculated first.

However, there's more to it than that - consider the following statement:

``````\$foo = 5 - 5 - 5;
``````

Like the previous statement, that can have two possible results, 5 and -5. Here is how those two possibilities would look if we made our intentions explicit with brackets:

``````\$foo = 5 - (5 - 5); \$foo = (5 - 5) - 5;
``````

So, what governs which answer is correct? The answer is operator associativity, which decides the direction in which operations are performed. The middle 5 has a minus on either side, but, because - is left-associative, the left-hand operation is performed first, giving the second possibility, and therefore -5.

If you are thinking that this all sounds incredibly complicated, relax - these rules only come into force if you fail to be explicit about your instructions. Unless you have very specific reason to do otherwise, you should always use brackets in your expressions to make your actual meaning very clear - both to PHP and to others reading your code.

If you have to rely on PHP's built-in rules for precedence and associativity, here's the complete list of association, ordered by the lowest-precedence operator to the highest-precedence operator:

 Associativity Operators left , left or left xor left and right print right = += -= *= /= .= %= &= |= ^= <<= >>= left ? : left || left && left | left ^ left & non-associative == != === !== non-associative < <= > >= left << >> left + - . left * / % right ! ~ ++ -- (int) (float) (string) (array) (object) @ right [ non-associative new

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!