Search code examples
phpoperator-precedence

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?


Solution

  • 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