> On Oct 14, 2023, at 16:30, Nikita Popov <nikita....@gmail.com> wrote: > > 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
I’m in favor of these functions, for all the same aforementioned reasons. Cheers, Ben -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://www.php.net/unsub.php