Re: [RFC] array_key_(first|last|index) functions proposal
| From: | John Bafford | Date: | Fri, 01 Jan 2016 21:51:36 +0000 |
| Subject: | Re: [RFC] array_key_(first|last|index) functions proposal | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-89958@lists.php.net to get a copy of this message | ||
> On Jan 1, 2016, at 16:38, Bishop Bettini <bishop@php.net> wrote:
>
> On Fri, Jan 1, 2016 at 3:44 PM, John Bafford <jbafford@zort.net> wrote:
> Happy New Year, everyone!
>
> I’d like to present the first new PHP RFC for this year, a proposal to add functions to
> easily get the first, last, or an arbitrary key (and value) by index from an array, taking advantage
> of PHP’s property that arrays are ordered maps.
>
> Thanks for submitting this RFC! I am +1, with one quibble: obtaining the value by reference
> seems non-sequitur to the function itself and PHP in general. IOW, this seems more PHPesque to me:
>
> // get the next to last value
> $key = array_key_index($arr, -2);
> $val = $arr[$key];
>
> Sincerely,
> bishop
While relatively rare for PHP, these aren't the only functions that have an optional second
return value by reference. (preg_match, preg_replace, str_replace, among others.)
I agree that that’s a bit unusual in terms of PHP, but, if you actually need both the key and the
value, this way you can do it in one call, rather than having to access the array and pull the value
out of it separately. The C code already has a reference to the hashtable bucket, so returning the
value if it’s needed is trivial.
-John