From: [EMAIL PROTECTED] Operating system: N/A PHP version: 4.1.1 PHP Bug Type: Feature/Change Request Bug description: An efficient way to access the last element of an array is sorely missed
There seems to be no easy and efficient way to access the last element of an array (assuming you don't already know the key to that element). The most concise, though not terribly efficient workaround I have discovered is... $array[array_pop(array_keys($array))] ...which first extracts all the keys of the array, then pops off the last key and uses it as an index into the array. Fairly easy to write and understand (though bulky), but horribly inefficient. Perhaps there is a place for new array_lastkey($array), array_firstkey($array), and array_element_key($array, $n) functions. The first of these functions would simply return the last key in the array (or null if the array is empty). The second would return the first key in the array (or null). In the third, $n would be a numeric index into the array, totally unrelated to the array's keys. A positive number would indicate how far "into" the array to go, a negative number would indicate how far "backward" into the array to go, while 0 or an out of bounds index might either quietly return a null or might throw an error or warning. Some Examples: $array = array( 1 => "One", "two" => "Two", -3 => "Minus Three" ); echo $array[array_firstkey($array)]; // returns "One" because array_firstkey() returns 1 echo $array[array_lastkey($array)]; // returns "Minus Three" because array_lastkey() returns -3 echo $array[array_element_key($array,1)]; // returns "One" because array_element_key() returns 1 echo $array[array_element_key($array,2)]; // returns "Two" because array_element_key() returns "two" echo $array[array_element_key($array,-2)]; // returns "Two" because array_element_key() returns "two" echo $array[array_element_key($array,-1)]; // returns "Minus Three" because array_element_key() returns -3 -- Edit bug report at: http://bugs.php.net/?id=15330&edit=1 -- PHP Development Mailing List <http://www.php.net/> To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] To contact the list administrators, e-mail: [EMAIL PROTECTED]