A solution would be to use a combination 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
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.
After this has been done the array's internal pointer will be at the end of the array. As pointed out in the comments, you may want to run reset() on the array to bring the pointer back to the beginning of the array.
A solution would be to use a combination 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
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.
After this has been done the array's internal pointer will be at the end of the array. As pointed out in the comments, you may want to run reset() on the array to bring the pointer back to the beginning of the array.
Although end() seems to be the easiest, it's not the fastest. The faster, and much stronger alternative is array_slice():
$lastKey = key(array_slice($array, -1, 1, true));
As the tests say, on an array with 500000 elements, it is almost 7x faster!
How to use array_key_last with numeric arrays in PHP?
How is array_key_last different from array_key_first?
- array_key_last gives the last key of an array.
- array_key_first gives the first key of an array.
100, "b" => 200];
echo array_key_first($data); // Output: a
echo array_key_last($data); // Output: b
?>
What happens when array_key_last is used on an empty array?
NULL.