php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #29732 Mod operator(%) doesn't work with negative integers
Submitted: 2004-08-18 14:39 UTC Modified: 2004-08-22 11:44 UTC
From: robinmessag at hotmail dot com Assigned:
Status: Closed Package: Documentation problem
PHP Version: Irrelevant OS: Windows 98SE
Private report: No CVE-ID: None
 [2004-08-18 14:39 UTC] robinmessag at hotmail dot com
Description:
------------
When doing the modulus of a negative number, PHP returns a bogus value. However, it is clearly doing the modulus, simply returning a negative answer.
In order to work around, one can add the modulus and mod again, but this is not a satisfactory solution IMHO.
This bug has been reported before and dismissed, however, modulus on negative numbers is correct and useful and this should be fixed or at least documented.

Reproduce code:
---------------
$hour=4;
$timedifference1=-6;
$timedifference2=-30;
$realtime=($hour+$timedifference1)%24;
$realtime2=($hour+$timedifference2)%24;
$realtime3=($hour+$timedifference2)%24;
$realtime3=(24+$realtime3)%24;
echo("The time is:$realtime or maybe $realtime2<BR>");
echo("The correct time is:$realtime3<BR>");

Expected result:
----------------
The time is:22 or maybe 22
The correct time is:22

Actual result:
--------------
The time is:-2 or maybe -2
The correct time is:22

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2004-08-18 14:47 UTC] derick@php.net
What was the previous bug number?
 [2004-08-21 17:06 UTC] robinmessag at hotmail dot com
I have since found Bug number #22527 which has some proper details on the workings of the % operator and the reasons behind it returning negative numbers.
I have changed the category to documentation problem.

Could I suggest changed to the documentation to indicate % gives the remainder from division, not the modulus which should always positive and also a note that this can give negative results.

I'm sorry this sounds like a petty thing but I have been caught out more than once by this behaviour which is at best an undocumented quirk.
 [2004-08-22 11:44 UTC] vrana@php.net
This bug has been fixed in the documentation's XML sources. Since the
online and downloadable versions of the documentation need some time
to get updated, we would like to ask you to be a bit patient.

Thank you for the report, and for helping us make our documentation better.

"Remainder $a % $b is negative for negative $a."
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Jul 23 20:00:03 2025 UTC