Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Operator Precedence and Associativity

Like many languages, PHP has a set of rules (known as operator precedence and associativity ) that decide how complicated expressions are processed. For example:

    $foo = 5 * 10 - 1;

Should $foo be 49 or 45? If you cannot see why there are two possibilities, break them up using parentheses like this:

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

In the first example, five is multiplied by ten, then one is subtracted from the result. But in the second example, ten has one subtracted from it, making nine, then that result is multiplied by five. If there is ambiguity in your expressions, PHP will resolve them according to its internal set of rules about operator precedence.

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

    $foo = 5 - 5 - 5;

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

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

In this example, it is operator associativity that governs which answer is correct. PHP has been programmed to consider each operator left-associative, right-associative, or non-associative. For example, given the make-believe operator μ, it might be right-associative and therefore treated like this:

    $foo = $a  $b  $c;
    // would be treated as...
    $foo = ($a  ($b  $c));

If PHP is programmed with μ as left-associative, it would start working from the left:

 $foo = $a $b $c; // would be treated as... ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page