php 搜索数组中的最高键/索引

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

Search for highest key/index in an array

phparrayskeyhighest

提问by Raffael Luthiger

How can I get with PHP the highest key/index in an array? I know how to do it for the values.

如何使用 PHP 获得数组中的最高键/索引?我知道如何为价值观做到这一点。

E.g. From this array I would like to get "10" as an integer value:

例如,从这个数组我想得到“10”作为一个整数值:

$arr = array( 1 => "A", 10 => "B", 5 => "C" );

I know how I could program it, but I was asking myself if there as a function for this as well.

我知道如何对其进行编程,但我问自己是否也有此功能。

回答by Gérald Cro?s

This should work fine

这应该可以正常工作

$arr = array( 1 => "A", 10 => "B", 5 => "C" );
max(array_keys($arr));

回答by Fabrizio D'Ammassa

You can get the maximum key this way:

您可以通过以下方式获得最大密钥:

<?php
$arr = array("a"=>"test", "b"=>"ztest");
$max = max(array_keys($arr));
?>

回答by JG Estiot

I had a situation where I needed to obtain the next available key in an array, which is the highest+1.

我遇到过需要获取数组中下一个可用键的情况,即最高的+1。

For example, if the array is $data=['1'=>'something,'34'=>'something else'] then I needed to calculate 35 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 needed 1 as next available key.

例如,如果数组是 $data=['1'=>'something,'34'=>'something else'] 那么我需要计算 35 以向数组中添加一个新元素,该元素的键高于任何其他人。在空数组的情况下,我需要 1 作为下一个可用键。

This is the solution that worked:

这是有效的解决方案:

    $highest = 0;
    foreach($data as $idx=>$dummy)
    {
        if($idx > $highest)$highest=$idx;
    }
    $highest++;

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.

无论是否为空数组,它都适用于所有情况。如果只需要查找最高键而不是最高键+1,则删除最后一行。如果数组为空,则您将获得值 0。

回答by Cfreak

$keys = array_keys($arr);
$keys = rsort($keys);

print $keys[0];

should print "10"

应该打印“10”

回答by AllisonC

Try max(): http://php.net/manual/en/function.max.phpSee the first comment on that page

试试 max(): http://php.net/manual/en/function.max.php看那个页面的第一条评论