-1

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 25 but it gives -1. I don't know, is there anything wrong with my expression?

PHP Output: PHP Output

Calculator: Calculator Output

Can anyone please identify, where is the problem?

Alena
  • 1,134
  • 6
  • 19
  • 45

2 Answers2

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
clinton3141
  • 4,751
  • 3
  • 33
  • 46
0

How about ?

$ cat test.php
<?php

function truemod($num, $mod) {
  return ($mod + ($num % $mod)) % $mod;
}

echo truemod(-1, 26).PHP_EOL;
?>

Output

$ php test.php 
25
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36