[php-src] Issue #9199: Function for getting first or last value from array
| From: | timint | Date: | Sat, 30 Jul 2022 01:11:56 +0000 |
| Subject: | [php-src] Issue #9199: Function for getting first or last value from array | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-242077@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/9199
Author: timint
### Description
I always felt PHP was lacking a convenient way of retrieving the first or last value from an array.
Looking at Stackoverflow this has been a burning hot topic. https://stackoverflow.com/questions/1921421/get-the-first-element-of-an-array
Some suggests shifting values from the array, some suggests moving the internal pointer. Some
suggests variable duplication and grabbing the values it's first or last numerical index key.
Examples seen:
```
$first = reset($arr); // Moves the pointer position
$first = array_shift(array_values($array)); // Throws strict error
foreach ($array as $first) break;
$first = $array[array_keys($array)[0]];
```
It doesn't need to be this complex. I am proposing adding
array_first() and
array_last()? To get the first or last value of an array without shifting it, or moving
the internal cursor.
To demonstrate:
```
// Get first value from array without shifting it or moving internal cursor
function array_first(array $array):mixed {
return reset($array) || false;
}
// Get last value from array without shifting it or moving internal cursor
function array_last(array $array):mixed {
return end($array) || false;
}
```
Comments or any help in creating an RFC is greatly appreciated.