Edit report at https://bugs.php.net/bug.php?id=61946&edit=1
ID: 61946 Comment by: phristen at yahoo dot com Reported by: phristen at yahoo dot com Summary: Implement array_first() and array_last() Status: Open Type: Feature/Change Request Package: Arrays related PHP Version: Irrelevant Block user comment: N Private report: N New Comment: This is a very basic operation, and it should be done in a single function call. I know about reset(), and I think it's ridiculous to have to call it every time I need to get the last element. It's also easy to 'forget' to reset it, and mess up your arrays. And it's gonna turn into a terrible mess when you have to use first and last in a single statement (e.g. comparing first to last inside an if()) P.S. I just used key() in my example to demonstrate that array_last should not change the internal pointer. Previous Comments: ------------------------------------------------------------------------ [2012-05-05 02:56:13] reeze dot xia at gmail dot com But from my point view, I'd like those functions. It really makes code more easy to read. ------------------------------------------------------------------------ [2012-05-05 02:44:42] reeze dot xia at gmail dot com Hi, phristen, you request can be easily satisfied by using: $array = array(1, 2, 3); reset($array); // point to the first element echo key($array); // the first key: 0 echo current($array); // first value end($array); // now point to the last values echo key($array); // last key echo current($array); // last value please refer to : http://www.php.net/manual/en/function.reset.php ---------------------- BTW: if you want to get all of keys of an array, you could use array_keys() but not key() :) Thanks. ------------------------------------------------------------------------ [2012-05-05 02:22:29] phristen at yahoo dot com Description: ------------ Retrieving the first or the last element of an array (without modifying the array) is a very common task. It is really annoying that PHP wouldn't come with built-in functions to do that. Can you please implement the following 2 array functions: array_first(array $array) - returns the first element of $array array_last(array $array) - returns the last element of $array Also consider implementing another pair of function to retrieve the keys: array_first_key and array_last_key. Test script: --------------- $test = array( 100 => "a", 200 => "b", 300 => "c", 400 => "d"); echo array_first($test)."\n"; echo array_last($test)."\n"; echo key($test)."\n"; echo implode(",", $test); Expected result: ---------------- a d 100 a,b,c,d Actual result: -------------- Fatal error: Call to undefined function array_first() on line 3 ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=61946&edit=1