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 开发者_如何学JAVAfalse depending if they key is the last of the array? Is there some kind of while()
statement I can use?
You could use end() and key() to get the key at the end of the array.
end($array);
$lastKey = key($array);
You can count
the array values:
$last_index = count($array) - 1;
But this won't work with associative arrays.
$is_2_lastone = array_pop(array_keys($array)) === 2;
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
If you're using PHP 7 >= 7.3.0 or PHP 8 you can use array_key_last()
$last_key = array_last_key( $arr );
精彩评论