This question already has an answer here:
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?
</div>