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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With