coerce() function
| From: | Dmitry Derepko | Date: | Wed, 10 Dec 2025 07:42:27 +0000 |
| Subject: | coerce() function | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-129578@lists.php.net to get a copy of this message | ||
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);
For sure, that could be different functions not to introduce another overloading function. Or range
arguments could be replaced with range(0, 10) function.
This letter is an intent to start discussion of any possible ways of developing this idea.
If we agree that the function has enough value to be bundled I’ll create RFC to push the idea
further.
So what do you think?
----------
Best regards,
Dmitrii Derepko.
@xepozz