如何返回数组中的最小键? [英] How can I return the minimum key in an array?

查看:61
本文介绍了如何返回数组中的最小键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数组中的键是否具有等效的 min()?

Is there an equivalent min() for the keys in an array?

给出数组:

$arr = array(300 => 'foo', 200 => 'bar');

如何返回最小密钥( 200 )?

How can I return the minimum key (200)?

这是一种方法,但我必须想象有一种更简单的方法.

Here's one approach, but I have to imagine there's an easier way.

function minKey($arr) {
    $minKey = key($arr);
    foreach ($arr as $k => $v) {
        if ($k < $minKey) $minKey = $k;
    }
    return $minKey;
}
$arr = array(300 => 'foo', 200 => 'bar');
echo minKey($arr); // 200

推荐答案

尝试一下:

echo min(array_keys($arr));

这篇关于如何返回数组中的最小键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆