php 检查键是否是数组中的最后一个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2260912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:46:32  来源:igfitidea点击:

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

phparrays

提问by tarnfeld

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?

值“c”的键为 2。是否有类似这样的代码is_end(2)返回 true 或 false,具体取决于它们的键是否是数组的最后一个?有while()什么我可以使用的声明吗?

回答by Yacoby

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

您可以使用end()key()来获取数组末尾的键。

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

回答by Felix Kling

You can countthe array values:

您可以count使用数组值:

$last_index = count($array) - 1;

But this won't work with associative arrays.

但这不适用于关联数组。

回答by useless

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

回答by Marius

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

假设您不使用关联数组,您可以使用count检查数组的长度。它会回来1+last index in array