Re: Two new functions array_first() and array_last()
| From: | Nikita Popov | Date: | Sat, 14 Oct 2023 20:29:28 +0000 |
| Subject: | Re: Two new functions array_first() and array_last() | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-121314@lists.php.net to get a copy of this message | ||
On Sat, Oct 14, 2023, at 20:00, David Grudl wrote:
> PHP lacks two very basic functions for working with arrays:
>
> - array_first() returning the first element of an array (or null)
> - array_last() returning the last element of the array (or null)
>
> While PHP has functions that return the first and last keys,
> array_key_first() and array_key_last(), it does not have more useful
> functions for values.
>
> a) What about reset() and end()?
> Programmers "abuse" the reset() and end() functions for this purpose.
> The problem is that these functions are used to move the internal
> pointer in the array. Which is why they have a name that is
> inappropriate when used in the sense of "return me the first element".
>
> Much worse, they shouldn't to be used to get first/last value, because
> they have a side effect (i.e. moving the pointer).
>
> Further, in the absence of an element, they return the obsolete false
> and not the currently expected null, which can be combined with the ??
> operator. In this they differ from the similar functions
> array_key_first() and array_key_last().
>
> b) What about $array[array_key_first($array)]?
>
> For such basic functions as returning the first and last item in an
> array, there should be a function in the basic package, not a
> workaround. Moreover, this requires having the array in a local
> variable, since $this->getFoo()[array_key_first($this->getFoo())]
> would be very inefficient and possibly incorrect.
>
> c) Two such functions were proposed and rejected during the
> array_key_first/last RFC
> (https://wiki.php.net/rfc/array_key_first_last)
>
> Yes, that was in 2018. At that time, functions like str_contains() or
> str_starts_with() wouldn't have even come into existence, just because
> there was an obscure way to do it without them. I believe we've moved
> on since then. Today we know how useful it is to use simple,
> easy-to-understand methods, both for programmers who write and read
> the code.
>
> DG
I'm in favor of adding these.
To add to what you already said, because reset/end modify the array, there's a good chance that
calling these functions will copy the whole array due to a modification you are not actually
interested in.
So basically you have the choice between calling end(), which is the wrong thing to do semantically
and may be slow, or using $array[array_key_last($array)], which is rather convoluted, and incorrect
if the array is potentially empty.
Regards,
Nikita