tags:

views:

92

answers:

4

How can i check if this key is the last in an array?

$array = array("a","b","c");

The value "c" would have the key 2, is there some code like this is_end(2) which returns true or false depending if they key is the last of the array? Or is there some kind of while() statement I can do?

+3  A: 

You could use end() and key() to get the key at the end of the array.

end($array);
$lastKey = key($array);
Yacoby
perfect! Thanks :D
tarnfeld
this doesnt work....
useless
maybe you mean something like: end($array);$lastKey = key($array);but you cant do it all in just 1 sentence.....
useless
@unless Yeah. Fixed.
Yacoby
A: 

You can count the array values:

$last_index = count($array) - 1;

But this won't work with associative arrays.

Felix Kling
A: 
$is_2_lastone = array_pop(array_keys($array)) === 2;
useless
A: 

Assuming you don't use an associative array, you could just check the length of the array, using count. It will return 1+last index in array

Marius