tags:

views:

77

answers:

6

$total = 30 - $nr1 / 13 - $nr2 - 6 * $nr3 - 3

I know we learned that in school but what is first (+ or - or * or /), where are the brackets or do i even need them ?

+4  A: 

You put brackets to priortizes what should be calculated first. In math though it starts from division, multiplication, subtraction and finally addition. So, here is the order of precedence for these:

  • division
  • multiplication
  • subtraction
  • addition

You can however override that rule by specifying brackets, for example you might want to have addition calculated first before anything else.

More Info:

Sarfraz
+1  A: 

See the chapter about Operator Precedence in the PHP manual.

nikc
A: 

First partentheses are calculated. Then multiplication and division. Then plus and minus. If you write say a*b/c, because multiplication doesn't precede division, nor does division precede multiplication, the computer will calculate it in the order it stands. So it will first calculate a*b and then divide that by c.

Calle
luckily (a*b)/c == a*(b/c)
Matt Ellen
@Matt Ellen - not in all cases... a*(b/c) can be zero in some cases where c>b is zero and so is a*0... IMO, it's always better to have (a*b)/c..
pinaki
+2  A: 

$total = 30 - ($nr1 / 13) - $nr2 - (6 * $nr3) - 3

I don't think extra brackets would harm. I always use them to improve readability

Im0rtality
+1, I can *never* remember the order of these operators =)
Jani Hartikainen
A: 
division, multiplication, addition, subtraction (/, *, +, -) 
Salil
A: 

the +- and */ pairs are of equal precedence. they are evaluated left to right.

stillstanding