RE: question about ? :

From: Date: Wed, 19 Jun 2002 13:00:15 +0000
Subject: RE: question about ? :
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-102918@lists.php.net to get a copy of this message
> OK, try this: why does > > $x = 3 + 5 - 7; > > produce different results from > > $x = 3 + (5 - 7); Really? It shouldn't produce different results for you -- they should both evaluate to '1'. However, the two expressions are evaluated in a different order because of the parentheses. Because addition is commutative (operands can be swapped around at will), and subtraction is really just addition of negative numbers, you can throw all the parentheses you want around that expression, and it'll still evaluate to be the same thing. Introduce multiplication/division into an equation, and that's a whole other story. So, here's how things get evaluated behind-the-scenes (only read on if you really have nothing else to do). In eighth grade math, they taught me order of operations as follows: P -> parentheses E -> exponentiation M -> multiplication D -> division A -> addition S -> subtraction That is, something higher on the list will be done before something lower on the list. In the case of MD and AS (multiplication/division and addition/subtraction), with no extraneous circumstances, operation will proceed from right to left. So this: 3 + 5 - 7 has all operators with equal precedence. It will first do '3+5', reducing the expression to: 8 - 7 which is a simple step to: 1 On the other hand, this: 3 + (5 - 7) has parentheses, which take a higher precedence than either addition or subtraction. So things inside of parentheses are evaluated before stuff outside. First reduction is: 3 + -2 which then evaluates to: 1 just as the previous one did. However, you can see how different paths were taken to get the same result. Joel -- [ joel boonstra | jboonstra@gospelcom.net ]

« previous php.general (#102918) next »