How to find the first element of an array with a value greater than X in PHP?

I have an array with numerical values, and I want to get the key of the first element with an equal or greater value 5. Is there a more elegant way than looping all the elements in foreach?

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

The algorithm itself works great, do not touch it.

However, you can add some feeds 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 is less effective; There is significant overhead that caused the closure of each item. If performance is paramount, use what you have and run with it.

+6
source

Source: https://habr.com/ru/post/1546844/


All Articles