How much is "((1 + 2 + $var1) * $var2) / 2 - 5"?

Posted by Simy202 on Tue 25 Jan 2011 08:20 AM — 3 posts, 16,738 views.

#0
I'm going through a php tutorial right now and this [url=http://www.phpkode.com/scripts/category/php-math/]PHP Math[/url] example below is driving me nuts. The exmaple was "((1 + 2 + $var1) * $var2) / 2 - 5", and all the rest of the code below is just me trying to figure it out.

The answer ends up being "7", but to me it looks like PHP is sayding "24 / -3 = 7" when it should be "24 / -3 = -8". What am I missing in this PHP Math issue?? Thanks!

<?php
$var1 = 3;
$var2 = 4;
?>
$var1 = 3;<br />
$var2 = 4;<br /><br />
<br />
<h1> ((1 + 2 + $var1) * $var2) / 2 - 5 = <?php echo((1 + 2 + $var1) * $var2) / 2 - 5; ?><br /> </h1>
<hr />
<br />
<br />
LEFT SIDE:<br />
(1 + 2 + $var1) * $var2 = <?php echo ((1 + 2 + $var1) * $var2); ?><br />
<br />
RIGHT SIDE:<br />
2 - 5 = <?php echo 2 - 5; ?><br />
<br />
24 / -3 SHOULD BE:
<h1>24 / -3 = <?php echo 24 / -3; ?><br /></h1>

That spits out:

$var1 = 3;
$var2 = 4;

((1 + 2 + $var1) * $var2) / 2 - 5 = 7

LEFT SIDE:
(1 + 2 + $var1) * $var2 = 24

RIGHT SIDE:
2 - 5 = -3

24 / -3 SHOULD BE:
24 / -3 = -8
Amended on Tue 25 Jan 2011 08:21 AM by Simy202
Australia Forum Administrator #1
Quote:


$var1 = 3;
$var2 = 4;

((1 + 2 + $var1) * $var2) / 2 - 5 = 7


Substituting:



((1 + 2 + 3) * 4) / 2 - 5 

= (6 * 4) / 2 - 5

= 24 / 2 - 5

= 12 - 5

= 7


You divide before you subtract. :-)
Amended on Tue 25 Jan 2011 09:54 AM by Nick Gammon
USA #2
First glance: you have to deal with the order of operations. "a / 2 - 5" (where I'm replacing everything else with 'a' for the moment) is a divided by 2, then subtracted by 5. But you suggest in your explanation that you want a / -3, right? So you need a / (2 - 5); the parentheses change the order of operations, causing the subtraction to occur before the division.

[EDIT]: Nick's post above explains why you get 7 right now, and my post explains what you need to do to get -8. :)