Hudzilla.org - the homepage of Paul Hudson
Contents > Simple variables and operators > Operators Wish List | Report Bug | About Me ]

3.12.7     Operator precedence and associativity

This is NOT the latest copy of this book; click here for the latest version.

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





<< 3.12.6 The execution operator   3.13 Summary >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
A PHP User - 07 Sep 2008

If we define the following array :

$my_array = array ('One' => 'Value 1', 'Two' => 'Value 2');

if you do :

$value = $my_array ['One'];

you get 'Value 1' stored in $value. What if you need associativity in both directions ?. For example if I need to get the value 'One' through 'Value 1' :

$value = my_array ['Value 1'];

then I get nothing as I expected. Is there anyway to do somthing like (unsing some operator) ? :

$my_array = array ('One' <=> 'Value 1', 'Two' <=> 'Value 2');

A PHP User - 07 Sep 2008

If we define the following array :

$my_array = array ('One' => 'Value 1', 'Two' => 'Value 2');

if you do :

$value = $my_array ['One'];

you get 'Value 1' stored in $value. What if you need associativity in both directions ?. For example if I need to get the value 'One' through 'Value 1' :

$value = my_array ['Value 1'];

then I get nothing as I expected. Is there anyway to do somthing like (unsing some operator) ? :

$my_array = array ('One' <=> 'Value 1', 'Two' <=> 'Value 2');

khwab.sheth@yahoo.com - 07 Sep 2008

<?php
echo '5Text' . 1 + 2 . '50';
?>

This should work like " echo ( 5Text . 1 ) + ( 2 . '50' ); " as concatenation operator has more precedence than addition operator.

Thats "echo 5Text1 + 250;"

that means " 5 + 250 " as when we convert 5Text1 to integer it gives 5.

Thats 255 but when we run, the result comes 750, can anyone explain how?

Thanks,

Khwab

khwab.sheth@yahoo.com - 07 Sep 2008

<?php
echo '5Text' . 1 + 2 . '50';
?>

This should work like " echo ( 5Text . 1 ) + ( 2 . '50' ); " as concatenation operator has more precedence than addition operator.

Thats "echo 5Text1 + 250;"

that means " 5 + 250 " as when we convert 5Text1 to integer it gives 5.

Thats 255 but when we run, the result comes 750, can anyone explain how?

Thanks,

Khwab

Illahi Bux - 07 Sep 2008

Explained very well precedence .. Well -done .

deathgod - 07 Sep 2008

Here's a tip, if you read all the above, you'll forget it straight away. So just browse through the list and print it out as refernce and stick it somewhere instead of straining to remember some obscure rules. The same could be done for the complete list of operators. Doing this should save you a few headaches i think.

O_O - 07 Sep 2008

O_o my brain hurtz

A PHP User - 07 Sep 2008

i think the right form is:
if (( $var == 'something' )||( $var == 'somethingelse' ))

tehbmwman - 07 Sep 2008

Does something like this work?

if ( $var = ( 'something' || 'somethingelse' ) )

A PHP User - 07 Sep 2008

yes, the PHP pprecedence and associativity rules follow those learned in math (or arithmetic) class

most other programming languages also follow those rules.

Sebbie - 07 Sep 2008

Does PHP still count the numbers according to normal mathematical rules, like without a guestion

5 - 5 - 5 = -5

according to mathematical rules.

Again, according to the same rules

5 - (5 - 5) = 5

and programming or PHP hasn't interfered with these rules has it? If you know the general mathematic rules, there's no room for confusion is there? Or am I missing something here?

Matt - 07 Sep 2008

Does math in php follow the normal math rules?

5 * 8 + 2 = 42
5 * 8 + 2 != 50

kimberly.eaves@usmiles.com - 07 Sep 2008

Very good explanation of precedence order. One of the best that I've read. Thanks.

A PHP User - 07 Sep 2008

very nice!



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is five plus five?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow