如何使用 php?我知道如何为价值观做这件事。
例如:从这个数组中,我想获取 10
作为 integer
值:
$arr = array(1 => "A", 10 => "B", 5 => "C");
我知道如何编码它,但我问自己是否有一个函数可以作为出色地。
How can I get the highest key/index
in an array with php? I know how to do it for the values.
E.g.: from this array I would like to get 10
as an integer
value:
$arr = array(1 => "A", 10 => "B", 5 => "C");
I know how I could code it but I was asking myself if there is a function for this as well.
发布评论
评论(7)
这应该可以正常工作
This should work fine
您可以通过以下方式获得最大密钥:
You can get the maximum key this way:
我遇到过这样的情况:我需要获取数组中的下一个可用键,即
最高 + 1
。例如,如果数组为
$data = ['1' => '某事,'34' => 'something else']
,然后我需要计算35
来将一个新元素添加到数组中,该元素的键值高于其他任何元素。在空数组的情况下,我需要1
作为下一个可用键。这是有效的解决方案:
它在所有情况下都有效,无论是否为空数组。如果您只需要找到最高键而不是
最高键 + 1
,请删除最后一行。如果数组为空,您将得到
0
值。I had a situation where I needed to obtain the next available key in an array, which is the
highest + 1
.For example, if the array is
$data = ['1' => 'something, '34' => 'something else']
, then I needed to calculate35
to add a new element to the array that had a key higher than any of the others. In the case of an empty array I needed1
as next available key.This is the solution that worked:
It will work in all cases, empty array or not. If you only need to find the highest key rather than
highest key + 1
, delete the last line.You will then get a value of
0
if the array is empty.应该打印“10”
should print "10"
假设您没有像
int -1
这样的负键assuming you don't have negative keys like
int -1
尝试 max() 函数,查看该页面上的第一条评论。
Try max() function, see the first comment on that page.