tags:

views:

853

answers:

3

How do you in a simple way get the last key of an array?

+9  A: 

A solution would be to use a combinaison of end and key (quoting) :

  • end() advances array 's internal pointer to the last element, and returns its value.
  • key() returns the index element of the current array position.


So, a portion of code such as this one should do the trick :

$array = array(
    'first' => 123,
    'second' => 456,
    'last' => 789, 
);

end($array);         // move the internal pointer to the end of the array
$key = key($array);  // fetches the key of the element pointed to by the internal pointer

var_dump($key);

Will output :

string 'last' (length=4)

i.e. the key of the last element of my array.

Pascal MARTIN
You should reset() the array pointer to be safe.
Pim Jager
@Pim : depends on what the OP wants to do with that array after *(might not be needed to call `reset()`)* ;; but you're right in pointing that function, which could be useful.
Pascal MARTIN
+2  A: 

Try using array_pop and array_keys function as follows:

<?php

$array = array(
    'one' => 1,
    'two' => 2,
    'three' => 3
);

echo array_pop(array_keys($array)); // prints three

?>
codaddict
This is really slow if your array has more than 1 thing in it. Please don't do this.
Andrey
A: 

Like this:

$keys = array_keys($array);
$lastKey = $keys[sizeof($array)-1];
Pim Jager
You can't use the return value as an array in php. Have you actually tried this?
Willi
Damn, your right, haven't done PHP in quite some time. Fixed it.
Pim Jager
This is really slow if your array has more than 1 thing in it. Please don't do this.
Andrey