Re: [DISCUSSION] Adding the "is_integer_safe()" function
| From: | Larry Garfield | Date: | Mon, 28 Jul 2025 15:32:01 +0000 |
| Subject: | Re: [DISCUSSION] Adding the "is_integer_safe()" function | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-128271@lists.php.net to get a copy of this message | ||
On Mon, Jul 28, 2025, at 8:00 AM, Alexandre Daubois wrote:
> Le lun. 28 juil. 2025 à 12:14, Gina P. Banyard <internals@gpb.moe> a écrit :
>> For naming, maybe the following pair of functions make sense?
>> - is_representable_as_int()
>
> Definitely, thank you for proposing. Having a pair of functions for
> bidirectional transformations makes much more sense than a single
> ambiguous function. Here are some quick specs for what these functions
> could do.
>
>
is_representable_as_int(mixed $value): bool checks if a given
> value
> can be losslessly converted to an integer.
>
> - Floats: returns true if the float is within PHP_INT_MIN to
> PHP_INT_MAX range AND has no fractional part
> - Strings: returns true if the string represents a valid integer
> within the platform's integer range
> - Always returns true for integers
> - Special float values: returns false for NaN, INF, -INF
>
> This gives the following example:
>
> ```php
> is_representable_as_int(42.0); // true
> is_representable_as_int(42.5); // false
> is_representable_as_int(2**31); // false on 32-bit, true on 64-bit
> is_representable_as_int(2**63); // false on both platforms
> is_representable_as_int("123"); // true
> is_representable_as_int("123.0"); // true
> is_representable_as_int("123.5"); // false
> is_representable_as_int(NAN); // false
> ```
Even without the precision loss question, such a function would be very useful when parsing input
data of unknown type (and thus is a string). "Can I cast this string to an int to use with an
int parameter without any loss" is currently not as simple as it ought to me. Providing a
single standardized function for that would be most welcome.
The name is quite long though. :-)
>> - is_representable_as_float()
The same argument applies here, although in most cases is_numeric() is close enough. A more precise
option would not be unwelcome, though.
--Larry Garfield