Can someone explain why I am getting error Division by zero when I want to use modulus operator and the second number is less than one (but more than 0 of course)
when I try
$a = 5
$b = 3
var_dump($a % $b);die; // result is as expected int(2)
but when I try this
$a = 5
$b = 0.5
var_dump($a % $b);die; // result is
Warning: Division by zero
bool(false)
PHP 5.4.4, debian 7
thanks
The modulo operator discards the fractional part of it's operands. From the documentation:
Operands of modulus are converted to integers (by stripping the decimal part) before processing.
This can be observed with the following:
$a = 5;
$b = 3.6;
var_dump($a % $b);die; // int(2)
To avoid this behavior, use the fmod method instead:
$a = 5;
$b = 0.5;
var_dump(fmod($a, $b));die; // float(0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With