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?
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.
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.
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.
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.
You could use end() and key() to get the key at the end of the array.
end($array);
$lastKey = key($array);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With