开发者

How to calculate correctly in php?

$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 ?


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:

  • http://php.net/manual/en/language.operators.precedence.php


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

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


See the chapter about Operator Precedence in the PHP manual.


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.


division, multiplication, addition, subtraction (/, *, +, -) 


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜