Re: coerce() function
| From: | Hans Henrik Bergan | Date: | Fri, 12 Dec 2025 17:46:46 +0000 |
| Subject: | Re: coerce() function | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-129597@lists.php.net to get a copy of this message | ||
On Wed, 10 Dec 2025 at 08:45, Dmitry Derepko <xepozzd@gmail.com> wrote:
> Hello,
>
> From time to time I need to write a few lines of code that usually look
> ridiculous:
>
> $var = $input === ‘yes’ ? ‘yes’ : ’no’
> $var = $input !== ‘yes’ ? ’no’ : $yes
> $var = $input > 10 ? 10 : $input
> $var = max(-10, min($input, 10)
>
> and many other variations.
> In Kotlin, I can use
coerceIn() extension function with strings
> /
> numbers / comparables, which allows me to write such lines more readable.
>
> 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);
>
>
btw many of these are already covered by filter_var,
$var = $input === ‘yes’ ? ‘yes’ : ’no’
$var = $input !== ‘yes’ ? ’no’ : $yes
$var = coerce($input, variants: [“yes”, “no”], default: “yes”);
$var = coerce($input, min: 0, max: 10, default: 5);
is very close to
$var = filter_var($input,FILTER_VALIDATE_BOOL);
$var = !filter_var($input,FILTER_VALIDATE_BOOL);
$var = filter_var($input,FILTER_VALIDATE_BOOL,
['options'=>['default'=>true]]);
$var = filter_var($input, FILTER_VALIDATE_INT,
['options'=>['min_range'=>0,
'max_range'=>10, 'default'=>5]]);
but if your syntax idea cover stuff like
$var = coerce($input, variants: [“yes”, “no”, "maybe"], default: “yes”);
then filter_var does not cover it (well, you could get creative with
FILTER_VALIDATE_CALLBACK, but that would be crazy, array_search would be
better lel)
but even so, your proposed syntax is certainly prettier than filter_var.