I am looking for an elegant way to get the first (and only the first) element of an array that satisfies a given condition.
Simple example:
Input:
[
['value' => 100, 'tag' => 'a'],
['value' => 200, 'tag' => 'b'],
['value' => 300, 'tag' => 'a'],
]
Condition: $element['value'] > 199
Expected output:
['value' => 200, 'tag' => 'b']
I came up with several solutions myself:
Iterate over the array, check for the condition and break when found
Use array_filter to apply condition and take first value of filtered:
array_values(
array_filter(
$input,
function($e){
return $e['value'] >= 200;
}
)
)[0];
Both seems a little cumbersome. Does anyone have a cleaner solution? Am i missing a built-in php function?
The shortest I could find is using current
:
current(array_filter($input, function($e) {...}));
current
essentially gets the first element, or returns false
if its empty.
If the code is being repeated often, it is probably best to extract it to its own function.