On Wed, 10 Dec 2025 at 08:45, Dmitry Derepko <[email protected]> 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.

Reply via email to