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
2010-02-27 17:11:58
You should reset() the array pointer to be safe.
Pim Jager
2010-02-27 17:14:37
@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
2010-02-27 17:16:01
+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
2010-02-27 17:12:07
This is really slow if your array has more than 1 thing in it. Please don't do this.
Andrey
2010-10-07 18:11:22
A:
Like this:
$keys = array_keys($array);
$lastKey = $keys[sizeof($array)-1];
Pim Jager
2010-02-27 17:13:27