 php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login go to bug id or search bugs for
Bug #22527 Submitted: Modulus returned negative value 2003-03-03 22:29 UTC 2003-03-04 01:23 UTC jaypedhskr at aol dot com Not a bug Math related 4.2.3 Unix No None
[2003-03-03 22:29 UTC] jaypedhskr at aol dot com
```Hi,

I had the following result from a PHP script, as seen from printing output variables:

-27 % 7 == -6

My understanding of the modulus function is that it returns the remainder from division, and that the remainder can never be negative.

I believe that is the standard mathematical definition.

So I think what should have been returned is 1 instead of -6.

That is

-27 = 7*(-4) + 1

-27 = 7*(-3) -6

I got around this by adding the the modulus value if the result was less than zero.  But I think a result of less than zero shouldn't occur.

Code snippet that ran into this:

\$T5 = \$D + \$T1 + \$Y + \$T2 + \$T3 - \$T4;
\$weekday = \$T5 % 7;

if (\$weekday < 0) {
\$weekday += 7;  // -27 % 7 = -6 case
}

Specific problem case:
\$T5 = 3 + 2 + 3 + 5 + 0 - 40; // -27
\$weekday = %T5 % 7; // -27 % 7 = -6

Thanks!

-Jay Pedersen

```

## History

[2003-03-04 01:23 UTC] rasmus@php.net
```Modulus has never been well-defined for negative values in computer languages.  It all comes down to whether the language truncates towards zero or towards negative infinity.  Computers have traditionally truncated towards zero, whereas mathematicians tend to truncate towards negative infinity.  Some languages like Fortran and Ada actually have two different modulus operators for this reason.  PHP just has one, and it truncates towards zero as has been the traditional and expected thing for programming languages to do.

So, given that, let's look at your numbers.  Modulus has to satisfy the relation: (a/b)*b + a%b = a
where a/b is an integer division where our truncation direction comes in.

(-27/7) * 7 + -27%7 = -27
( -3  ) * 7 + -27%7 = -27
-21 + -27%7   = -27
-27%7   = -27+21
-27%7   = -6

In fact, the ISO standard for the C programming language, in which PHP is written, defines integer division and modulus operators to perform truncation towards 0 and not towards negative infinity.  We don't really have a strict language definition for PHP, but if we did, we would most likely follow the lead of languages like Fortran, C and C++ and specify truncation towards zero to be as consistent as possible with other languages.

``` Copyright © 2001-2020 The PHP Group All rights reserved. Last updated: Tue Sep 29 15:01:25 2020 UTC