如何在PHP中找到值大于X的第一个数组元素? [英] How to find first array element with value greater than X in PHP?

查看:23
本文介绍了如何在PHP中找到值大于X的第一个数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数值数组,我想获取第一个元素的键,它的值等于或大于 5.有没有比在 foreach 中循环所有元素更优雅的方法?

I have array with numeric values and I want to get key of first element which has value equal or greater than 5. Is there more elegant way than looping all elements in foreach?

// "dirty" way
foreach ([0, 0, 4, 4, 5, 7] as $key => $value) {
    if ($value >= 5) {
        echo $key;
        break;
    }
}

推荐答案

算法本身非常好,不要碰它.

The algorithm itself is perfectly fine, don't touch it.

也就是说,您可以通过编写通用搜索功能来添加一些功能区:

That said, you could add some ribbons by writing a generic search function:

// find first key (from beginning of $a) for which the corresponding
// array element satisfies predicate $fn
function array_find(array $a, callable $fn)
{
    foreach ($a as $key => $value) {
        if ($fn($value, $key, $a)) {
            return $key;
        }
    }
    return false;
}

$key = array_find([0, 0, 4, 4, 5, 7], function($value) {
    return $value >= 5;
});

现在,虽然这是一种更优雅的方法,但效率较低;在每个项目上调用闭包都有相当大的开销.如果性能最重要,请使用您拥有的并运行它.

Now, although this is a more elegant approach, it's less efficient; there's a considerable overhead of calling the closure at each item. If performance is paramount, use what you have and run with it.

这篇关于如何在PHP中找到值大于X的第一个数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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