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