How to divide numbers without remainder in PHP?

前端 未结 6 1880
抹茶落季
抹茶落季 2020-12-29 18:08

How does one divide numbers but exclude the remainder in PHP?

6条回答
  •  情歌与酒
    2020-12-29 18:28

    In addition to decisions above like $result = intval($a / $b) there is one particular case:

    If you need an integer division (without remainder) by some power of two ($b is 2 ^ N) you can use bitwise right shift operation:

    $result = $a >> $N;
    

    where $N is number from 1 to 32 on 32-bit operating system or 64 for 64-bit ones.

    Sometimes it's useful because it's fastest decision for case of $b is some power of two.

    And there's a backward (be careful due to overflow!) operation for multiplying by power of two:

    $result = $a << $N;
    

    Hope this helps for someone too.

提交回复
热议问题