tags:

views:

88

answers:

3

I have a standard associative array in PHP. what's the simplest way to get the last key in that array?

example:

$foo = array('key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3');

and i would like to get 'key3';

+8  A: 
$keys = array_keys($foo);
$last = end($keys);

you need to pass an actual variable to end, you can't put another function inside there.

Tesserex
+9  A: 

Fastest method would be this:

end($foo);
$last = key($foo);

Tesserex's method is unnecessarily resource hungry when you don't need all keys.

Emil Vikström
yes, that first upvote came from me.
Tesserex
;-) I even looked for some nice way to save the internal pointer so you could go back afterwards, but couldn't find any nice way to do it...
Emil Vikström
@Emil Good point, I've also just looked and I don't think there's a way to save the pointer state (no function exposes `zend_hash_get_pointer` and `zend_hash_set_pointer`). Would be a nice addition.
Artefacto
`reset($foo);` http://php.net/reset
Justin Johnson
@Justin Johnson It rewinds the pointer, doesn't put it where it were.
Artefacto
Oh right. I believe the only way to do that is to duplicate the array, and work on the duplicate .... which isn't very efficient.
Justin Johnson
A: 

The following is not the simplest, but it will may be much happier to deal with large (in terms of number of elements; though will probably be better for most uses) arrays than the other answers.

$last_key = key(array_slice($subject, -1, 1, true));

educated guess, may not be true for all cases

salathe
I tend to disagree. I tried all three solutions on an array with 10000 integer values and my solution was about 20 times faster than yours. Results in seconds, measure by microtime(): typical time for yours: 0.00013. Typical time for mine: 0.0000069. Typical time for Tesserex: 0.003.
Emil Vikström
On a small array (hundred integer values): Yours: 0.000015. Mine: 0.000005. Tesserex: 0.00003
Emil Vikström
I'm not going to starting giving benchmark results suffice to say, I tend to disagree. Either way, the OP was after the **simplest** which mine certainly is not. :-)
salathe
@Emil Unless you're finding the end of 100's of huge array, micro-benchmarking is a useless discussion.
Justin Johnson