Hi Dmitry, On 10 December 2025 07:42:27 GMT, Dmitry Derepko <[email protected]> wrote:
>I suggest to add such function to PHP. The examples above may look like the >following > >$var = coerce($input, variants: [“yes”, “no”], default: “yes”); >$var = coerce($input, min: 0, max: 10, default: 5); >$var = coerce($input, min: 0, max: 10, default: 5); > >For sure, that could be different functions not to introduce another >overloading function. Or range arguments could be replaced with `range(0, 10)` >function. My first thought was that the min/max variant would be covered by the recently-accepted clamp() function: https://wiki.php.net/rfc/clamp_v2 Looking closer, I see that you want to default to a specific value, not the nearest, so it's not quite the same. I think combining both tasks into one function is definitely the wrong approach. PHP doesn't have function overloading, and although you can partially stimulate it with nullable and optional parameters, the whole thing ends up very messy compared to just having separate functions. Using range() to pass in an array would be less efficient than min and max, but maybe good enough for small ranges. Perhaps in future we will have a separate "lazy range" type, which could then be handled as a special case. In general, I don't think it's a function that I'd use often, but it seems a reasonable enough addition to the language. Thanks, Rowan Tommins [IMSoP]
