Re: [RFC][Under Discussion] Add functions array_key_first()and array_key_last()
| From: | Levi Morrison | Date: | Wed, 20 Jun 2018 13:55:00 +0000 |
| Subject: | Re: [RFC][Under Discussion] Add functions array_key_first()and array_key_last() | ||
| References: | 1 2 3 4 5 6 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-102321@lists.php.net to get a copy of this message | ||
On Wed, Jun 20, 2018 at 3:17 AM Woortmann, Enno <enno.woortmann@web.de> wrote:
>
> Hi Levi,
>
>
> Am 20.06.2018 um 04:47 schrieb Levi Morrison:
> > list($key, $value) = array_first($input);
> > // $key will be null if the call failed
> >
> > list($key, $value) = array_last($input);
> > // $key will be null if the call failed
>
> Your proposed functions would be implementable with the internal
> functions but I think this approach doesn't provide a clean function
> interface as it forces the user to evaluate the wanted value from the
> returned array structure by using either the list() construct or
> something like $key = array_first($input)[0];
>
> I believe two functions with this interface will be confusing and less
> intuitive for the developer.
> If I use a function I expect it to give me a return value which I can
> use without any further post processing $wantedValue =
> fancyFunction($someInput);
Your wish cannot be granted for
array_value_last and
array_value_first; you cannot know by itself if there is a failure
condition. As proposed you have to write:
if (!empty($input)) {
$value = array_value_last($input)
// do something
}
This is not "clean". In contrast here is with my proposal:
if ([$key, $value] = array_last($input) {
// do something
}
If I need the last/first key and value (which is a real use-case and
why I thought of this in the first place) then in your proposal I have
to do:
if (!empty($input)) {
$key = array_key_last($input);
$value = array_value_last($input);
}
Or use the key to get the value; roughly the same amount of code.
Either way is not as clean as:
if ([$key, $value] = array_last($input) {
// do something
}
Hopefully I have shown that for various use-cases the proposed
interface is cleaner and that you cannot argue against it on those
grounds.
Adding 4 functions which cover 4 use-cases, with ugly names, and 2 of
them having poor failure semantics is not a good direction. Adding
only 2 functions which cover 6 use-cases, with nice names, and good
failure conditions is better. Please reconsider.