On Tue, Aug 26, 2025, at 1:36 PM, Tim Düsterhus wrote:
> Hi
>
> On 8/26/25 16:48, Larry Garfield wrote:
>> I have multiple times just recently had need of "I have a numeric string, should I
>> cast it to an int or a float?", for which an is_representable_as_int() function (or similar)
>> would be quite helpful, and neater than the messy solution I usually use.
>
> It would've been nice to know what that use-case is, rather than just
> knowing that you had that use-case.
>
> I'm having a hard time thinking of something where I don't a-priori know
> what type I expect to get and would need to inspect the value to make a
> decision.
>
> I see how having a function that safely coerces a string into an int,
> returning null if coercion fails, basically intval() with better error
> handling and taking only strings, could be useful, but that's not what
> is being asked here.
>
> Best regards
> Tim Düsterhus
When doing generic serialization, the input is often always-strings (eg, environment variables, HTTP
Query parameters, etc.) When doing generic code (not type generics, but "works on
anything" kind of generic), I often have to resort to this:
https://github.com/Crell/EnvMapper/blob/master/src/EnvMapper.php#L88
Which gets the job done, but feels ugly to me.
Even if I know what the target type is, I still need to ask the question "so does this string
match the target type?"
https://github.com/Crell/Carica/blob/master/src/Middleware/NormalizeArgumentTypesMiddleware.php#L73
"I have a string, the parameter wants an int, is that even possible?" Being able to
replace that floor() nonsense with is_integerable() (by whatever name) would make my life a lot
easier.
For float, is_numeric() is already sufficient for my purposes. I just need to be able to
differentiate between "3" and "3.14" to cast to the correct type.
--Larry Garfield