I have an array like this:
我有一个像这样的数组:
array[0] = "hello0"
array[1] = "hello1"
array[2] = "hello2"
Now I want to get the last key '2' of the array. I cant use end() because that will return the value 'hello2'.
现在我想获得数组的最后一个键'2'。我不能使用end()因为它将返回值'hello2'。
What function should I use?
我应该使用什么功能?
3 个解决方案
#1
2
If the keys are not continuous (i.e. if you had keys 1, 5, 7, for example):
如果键不连续(例如,如果你有键1,5,7,例如):
$highest_key = rsort(array_keys($myarray))[0];
If they are continuous, just use count($myarray)-1
.
如果它们是连续的,只需使用count($ myarray)-1。
#2
8
end() not only returns the value of the last element but also sets the internal pointer to the last element. And key() returns the key of the element this internal pointer currently ...err... points to.
end()不仅返回最后一个元素的值,还将内部指针设置为最后一个元素。并且key()返回当前内部指针的元素的键...错误...指向。
$a = array(1=>'a', 5=>'b', 99=>'d');
end($a);
echo key($a);
prints 99
打印99
#3
0
count($array) - 1
Won't work if you've added non-numeric keys or non-sequential keys.
如果您添加了非数字键或非顺序键,则无效。
#1
2
If the keys are not continuous (i.e. if you had keys 1, 5, 7, for example):
如果键不连续(例如,如果你有键1,5,7,例如):
$highest_key = rsort(array_keys($myarray))[0];
If they are continuous, just use count($myarray)-1
.
如果它们是连续的,只需使用count($ myarray)-1。
#2
8
end() not only returns the value of the last element but also sets the internal pointer to the last element. And key() returns the key of the element this internal pointer currently ...err... points to.
end()不仅返回最后一个元素的值,还将内部指针设置为最后一个元素。并且key()返回当前内部指针的元素的键...错误...指向。
$a = array(1=>'a', 5=>'b', 99=>'d');
end($a);
echo key($a);
prints 99
打印99
#3
0
count($array) - 1
Won't work if you've added non-numeric keys or non-sequential keys.
如果您添加了非数字键或非顺序键,则无效。