Re: [VOTE] array_key_first(), array_key_last(), array_value_first(), array_value_last()
| From: | Côme Chilliet | Date: | Mon, 16 Jul 2018 08:26:14 +0000 |
| Subject: | Re: [VOTE] array_key_first(), array_key_last(), array_value_first(), array_value_last() | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-102835@lists.php.net to get a copy of this message | ||
Le vendredi 13 juillet 2018, 16:48:29 CEST Levi Morrison a écrit :
> Below is a proof-of-concept for the
array_offset function
> [mentioned
> by Nicolas Grekas][2] (which by the way, neither the RFC author nor
> anyone else responded to this suggestion) that is simply a convenience
> wrapper over array_slice:
>
> function array_offset(array $input, int $offset): ?array {
> $slice = array_slice($input, $offset, 1, true);
> return count($slice) ? $slice : null;
> }
>
> $assoc = ['one' => 1, 'two' => 2, 'three' => 3];
> $packd = range(1, 4);
>
> var_dump(array_offset($assoc, -1));
> var_dump(array_offset($packd, -1));
>
> var_dump(array_offset($assoc, 0));
> var_dump(array_offset($packd, 0));
>
> Of course, the array_slice function can be used to build all of
> the
> functions described in the RFC, as well.
How would you do that, since array_slice still gives you an associative array as a result?
array_values(array_slice($array, -1, 1, true))[0] is way less readable than
array_last_value($array), and the question «how efficient is that and how many array copies are
made?» becomes complicated to answer for non-initiated.
While with a native function you expect it to be as efficient as possible to do what you ask it.
(And as you state in your other mail in the end this array_slice solution is not as efficient as you
expected)
I would have been fine with array_key($array, $offset=0) and array_value($array, $offset=0) instead
of the 4 functions from the RFC to be able to use any offset.
Côme