开发者

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

开发者 https://www.devze.com 2022-12-20 16:03 出处:网络
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 开

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 );

0

精彩评论

暂无评论...
验证码 换一张
取 消