Ahmad
Ahmad

Reputation: 95

Confusing Operator Precedence 2 / 5 * 3 in PHP

As PHP's Manual shows, the following operators have the same priority (left associativity):

* / %

So, It means:

echo 2 / 5 * 3

must display 7.5! because the multiplication will perform first, 5 * 3 = 15 then the quotient will divided by 2.

But when I run that code, PHP code outputs 1.2!

Could anyone please to understand what's going on?

Upvotes: 1

Views: 110

Answers (4)

Abdulla Nilam
Abdulla Nilam

Reputation: 38584

There is an order to execute arithmetic operations. which call short PEMDAS

  1. () - brackets
  2. / - deviation
  3. * - multiplication
  4. + - add
  5. - - min

This will(2 / 5 * 3) execute in above order


So what happen on here 2 / 5 * 3

  1. 2/5 = 0.4
  2. 0.4*3 = 1.2

To fulfill your requirement

  1. 5 * 3 = 15
  2. 15 / 2 = 7.5

So you have to do (5 * 3) / 2 or 2 / (5 * 3)


PHPFiddle Preview

Upvotes: 1

tino.codes
tino.codes

Reputation: 1507

As you can see here: http://php.net/manual/en/language.operators.precedence.php

the operator * / and % has the same precedence. * has the same precedence as /.

Upvotes: 0

Covik
Covik

Reputation: 862

It's left to right 2/5=0.4 0.4*3=1.2

Upvotes: 0

Andrius
Andrius

Reputation: 5939

Same priority means that everything will happen from left to right.

Meaning that it won't multiply first. The order in which * / % was written in the manual does not matter.

  • 2 / 5 = 0.4
  • 0.4 * 3 = 1.2

Also, by your logic, you should be getting 1.(3) but that's not the point.

Upvotes: 3

Related Questions