Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find first array element with value greater than X in PHP?

Tags:

arrays

php

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;
    }
}
like image 310
Livia Martinez Avatar asked Jul 02 '14 11:07

Livia Martinez


1 Answers

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.

like image 187
Ja͢ck Avatar answered Oct 16 '22 07:10

Ja͢ck