> On Dec 10, 2025, at 6:00 PM, Rowan Tommins [IMSoP] <[email protected]> > wrote: > > 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]
Thanks for your thoughts. I agree that it’s better to have a few separate functions for different use cases. Regarding the lazy ranges, basically, it’s kind of `iterable`, but with bounds. I think it could be done as the others are: new IntRangeIterator(start: 0, end: 10, inclusive: true) / or as a new function range_iterator / or as a new flag argument in the original range function. So, there are could be a function with: - manual range bounds — strings — ints — enums? - iterator range bounds — IntRangeIterator(start: 0, end: 10, inclusive: true) — CharRangeIterator(start: ‘A', end: ‘D', inclusive: true) — Any other `iterable`, including Generators and regular arrays Actually, looks quite reasonable to re-use iterables. Nice catch, I really like it. ---------- Best regards, Dmitrii Derepko. @xepozz
