tarnfeld
tarnfeld

Reputation: 26556

Checking if a key is the last element in an array?

How can I check if this key is the last element 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? Is there some kind of while() statement I can use?

Upvotes: 10

Views: 33665

Answers (5)

Haddock-san
Haddock-san

Reputation: 895

If you're using PHP 7 >= 7.3.0 or PHP 8 you can use array_key_last()

$last_key = array_last_key( $arr );

Upvotes: 0

Yacoby
Yacoby

Reputation: 55445

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

end($array);
$lastKey = key($array);

Upvotes: 22

Marius
Marius

Reputation: 58931

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

Upvotes: 0

useless
useless

Reputation: 1906

$is_2_lastone = array_pop(array_keys($array)) === 2;

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816422

You can count the array values:

$last_index = count($array) - 1;

But this won't work with associative arrays.

Upvotes: 5

Related Questions