Hello Internals,
I would like to gather feedback on the proposal to add an
"is_integer_safe()" function to PHP. The idea came to me while
replying to a thread [1], but I think creating a discussion is more
appropriate.
Here are a few reasons I think this would be useful:
- PHP automatically converts integers that exceed PHP_INT_MAX to
float, which can cause undetected precision loss. This function would
allow checking that an integer remains within safe bounds before
critical operations ;
- Integer limits vary between 32-bit and 64-bit systems. This function
would provide a standardized way to check the portability of integer
values across different architectures ;
- This would improve code readability. We had the case in Symfony [2]
to implement a JSONPath crawler, and the solution feels hacky to say
the least ;
- PHP already has functions like `is_finite()` and `is_nan()` for
floats. Adding `is_integer_safe()` would logically complete this set
of type validation functions.
- Of course more optimized than dealing with strings and using
arithmetic operators on strings ;
- As PHP continues to evolve towards stricter type safety
(strict_types, typed properties, etc.), having more granular type
validation functions supports this direction.
If this proposition gets some interest, I'll take care of the
implementation in the engine. I guess it would also require an RFC.
Best,
Alex
[1] Introduce PHP_INT_MAX_SAFE constant similar to JS's Number.MAX_SAFE_INTEGER constant - Externals
[2] symfony/src/Symfony/Component/JsonPath/JsonPathUtils.php at d3a0df0243e1c68598fa066eaa6cd0cf39f256dc · symfony/symfony · GitHub