php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #15330 An efficient way to access the last element of an array is sorely missed
Submitted: 2002-02-01 14:07 UTC Modified: 2002-02-04 16:15 UTC
Votes:1
Avg. Score:4.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: hek at loudoun-net dot com Assigned:
Status: Not a bug Package: Feature/Change Request
PHP Version: 4.1.1 OS: N/A
Private report: No CVE-ID: None
 [2002-02-01 14:07 UTC] hek at loudoun-net dot com
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

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2002-02-01 14:38 UTC] matslin at orakel dot ntnu dot no
While there is no way to set the internal pointer (afaik) to a given element #, you can set the pointer to the first/last/next/previous item.

http://se.php.net/manual/en/function.end.php

end --  Set the internal pointer of an array to its last element.

--
mats
 [2002-02-01 15:11 UTC] torben@php.net
These functions have been available for a long time and are
well documented in the manual--see the previous comment.


Torben
 [2002-02-04 10:03 UTC] hek at loudoun-net dot com
Yes, I am aware of end().  It certainly has a purpose and a use, but it isn't at all the same as what I was suggesting.

Frankly, I never use the "internal pointer" features of arrays, as they were at first alien to me, and later seemed unreliable when I thought I understood them.

Providing altenative methods for ding things in  programming language as otherwise accomodating as PHP, seems to me, precisely in character with its philosophy.

I would be more than happy to contribute these functions myself, if someone will point me in the right direction to do so.  Thank you.

--HaigEK
 [2002-02-04 10:30 UTC] hek at loudoun-net dot com
Aha!  Now I see array_slice() -- much closer to that I was proposing.  However, it still does not get you the value you are after directly, but an array (sans original keys) you then have to delve into for your value.  Still, closer.

Also, I've found the well-hidden information on getting a CVS account, so no need for that pointer now.  Thanks again.

--HaigEK
 [2002-02-04 16:15 UTC] torben@php.net
Well, if you wouldn't worry about using the internal 
pointers, you'd have an easier time of this. :) You can
do what you need very trivially (note that I'm not saying
these functions shouldn't be added to PHP, just that this
is already easy to do in userland):

For instance:

function array_first_key($array) {
    reset($array);
    return key($array);
}

function array_last_key($array) {
    end($array);
    return key($array);
}

...for the *_value() versions, use current() instead of
key(). For the index searcher, you can do something like:


function array_element_key($array, $element) {
    if (abs($element) > count($array)) {
        return false;
    }

    if ($element < 0) {
        for ($i = -1, end($array); $i > $element; $i--, prev($array));
    } else {
        for ($i = 0, reset($array); $i < $element; $i++, next($array));
    }

    return key($array);
}

...and so on.


Hope this helps until (if) these get added to the language.
Email me privately if you want the whole batch of 
functions.


Torben
 [2002-02-07 09:22 UTC] hek at loudoun dot net
Did I already reply to this?  Please accept my apologies if I did, and have just misplaced the reply.

Thank you for the suggested code.

Turns out that all along end() does exactly what I've wanted -- I just didn't catch the part at the end of the manual page for it, where it says the return value is the value of the last element in the array.  I think I was misled by matslin@orakel.ntnu.no's line:

>> end --  Set the internal pointer of an array to its last element.

Sorry for all the bother I've been.  Still think that the functions I suggested would do no harm in the library, espescially as then they could be even more efficient than if implemented as user functions.

But thanks again.

--Haig
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Apr 27 22:01:28 2024 UTC