Alena Alena - 3 years ago 187
PHP Question

Strange Modulus Operator Result - PHP

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;

The answer should be
but it gives
. I don't know, is there anything wrong with my expression?

PHP Output:
PHP Output

Calculator Output

Can anyone please identify, where is the problem?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download