>
> 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 would love to have these functions in PHP as well.

With the bikeshed risk, perhaps it makes more sense to have the
functions named `array_value_first` and `array_value_last`, because we
already have `array_key_first` and `array_key_last` functions?

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to