I am working on a PHP application and mathematical operation was resulting wrong answer which was displaying wrong results. So, I started digging down and after few hours effort I was able to detect the issue.
Here is the problematic Expression:
echo -1 % 26;
25
-1
This is the expected behaviour. From the PHP manual
The result of the modulo operator % has the same sign as the dividend — that is, the result of
$a % $b
will have the same sign as$a
If the sign of the dividend (the part to the left of the %
) changes, the result will also change. You can find the positive equivalent of a negative remainder by adding the divisor. -1 is equivalent to 25 modulo 26 since -1 + 26 = 25.
Hence you can do the following to get the positive result:
function modulo($dividend, $divisor) {
$result = $dividend % $divisor;
return $result < 0 ? $result + $divisor : $result;
}
$calculation = modulo(-1, 26); // 25
$calculation2 = modulo(51, 26); // 25