Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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?

like image 391
tarnfeld Avatar asked Feb 14 '10 11:02

tarnfeld


People also ask

How do you check if an item is last in an array?

1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.

How do I get the last array key?

You can use the end() function in PHP to get the last element of any PHP array. It will set the internal pointer to the last element of the array and return its value.

How do you check if an element is the last element in an array Java?

Get the ArrayList with elements. Get the first element of ArrayList with use of get(index) method by passing index = 0. Get the last element of ArrayList with use of get(index) method by passing index = size – 1.

How do you check if a key is in an array?

Answer: Use the PHP array_key_exists() function You can use the PHP array_key_exists() function to test whether a given key or index exists in an array or not. This function returns TRUE on success or FALSE on failure.


1 Answers

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

end($array);
$lastKey = key($array);
like image 104
Yacoby Avatar answered Sep 23 '22 21:09

Yacoby