1
$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
  • Unless this is homework, use brackets, so you don't need to remember precedence rules Commented Aug 3, 2010 at 9:49
  • Suggestion: take an algebra review class. Seriously. Commented Aug 3, 2010 at 10:04
  • I realize the title says "php," but this is really a math question, not a programming question. (I suppose you could argue that some programming language could implement math in some unconventional way, like using the + symbol to mean division, but that's pretty far-fetched.) Commented Aug 21, 2012 at 14:13
  • 6 Letters.. PEMDAS. I suggest you Google it. Commented Aug 22, 2012 at 16:17

6 Answers 6

4

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:

Sign up to request clarification or add additional context in comments.

1 Comment

This isn't 100% correct is it? Algebra (and C like languages in general) parse left to right, with equal but higher precedence given to [/|*] and equal but lower precedence given to [-|+], in respect to these four operators (where [] denotes some set of operators, and | denotes a separation of that sets elements, indicating only one can be chosen)
3
$total = 30 - ($nr1 / 13) - $nr2 - (6 * $nr3) - 3 

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

Comments

2

See the chapter about Operator Precedence in the PHP manual.

Comments

1

First partentheses are calculated. Then multiplication and division. Then plus and minus. If you write say ab/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 ab and then divide that by c.

1 Comment

@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..
1
division, multiplication, addition, subtraction (/, *, +, -) 

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.