php 获取数组最后一个元素的key

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6251331/
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 23:47:36  来源:igfitidea点击:

Get key of the last element in an array

phparraysindexing

提问by dotty

Hay, i have an array which contains a set of arrays, here's an example.

嘿,我有一个包含一组数组的数组,这是一个例子。

array(
    [0]=>array('name'=>'bob'),
    [2]=>array('name'=>'tom'),
    [3]=array('name'=>'mark')
)

How would i get the last item in the array, and returns it's key.

我将如何获取数组中的最后一项,并返回它的键。

So in the above example it would return 3.

所以在上面的例子中它会返回 3。

回答by cem

end($array);
echo key($array)

This should return the key of the last element.

这应该返回最后一个元素的键。

回答by Dunhamzzz

Try $lastKey = end(array_keys($array));

尝试 $lastKey = end(array_keys($array));

回答by skowron-line

<?php
$a = array(
    0=>array('name'=>'bob'),
    2=>array('name'=>'tom'),
    3=>array('name'=>'mark')
);


$b = array_keys($a);
echo end($b);

?>

something like this

像这样的东西

回答by Alix Axel

Another option:

另外一个选项:

$last_key = key(array_slice($array, -1, true));

回答by Atif Tariq

You can create function and use it:

您可以创建函数并使用它:

function endKey($array){
end($array);
return key($array);
}

$array = array("one" => "apple", "two" => "orange", "three" => "pear");
echo endKey($array);