Re: Proposal for floored division and modulo functions

From: Date: Mon, 22 Aug 2022 17:49:14 +0000
Subject: Re: Proposal for floored division and modulo functions
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to internals+get-118452@lists.php.net to get a copy of this message
On Mon, Aug 22, 2022 at 4:22 AM Daniel Wolfe <dwo@the-wolfeden.com> wrote: > For the first four instances, the function works as intended since the > timestamps are non-negative numbers. However, for the fifth example, > since the date is before 1970, the timestamp is going to be negative > resulting in an ostensible array key which will also be negative. The > floor technique would instead return a positive array key. > > …since the time of the day for each of these dates is the same (i..e., > 1:46 AM), it *should* calculate 6,360 seconds since midnight for each > instance. It does this correctly for the first four instances, but the > fifth instance reports -80,040 seconds—a meaningless result. The floor > technique would return the same result as the others. > Both these examples and any others can already be solved very easily in userland PHP, either ad-hoc specific to what you're doing or by user implementations of floor_div and floor_mod. No doubt you are already aware it's as simple as: function floor_mod($a, $b) { return $a - ($b * floor($a / $b)); } That said, while my preference is *usually* "don't add stuff to PHP which users can easily do themselves", I do think in the case of certain ubiquitous and useful scalar operations, there's a good case for it being supported out the box. And this has been done, many times - functions like str_contains and array_key_last were things which could be easily done in userland and easily supported through polyfills for older PHP versions. The bit I think I might not like is these being functions, floor_div and floor_mod. They may be easily confused with the similarly named and existing fdiv and fmod functions. Wouldn't new operators, // and %% respectively, be preferable? -Dave

« previous php.internals (#118452) next »