Search code examples
phparray-filter

First element of array by condition


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:

  1. Iterate over the array, check for the condition and break when found

  2. 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?


Solution

  • There's no need to use all above mentioned functions like array_filter. Because array_filter filters array. And filtering is not the same as find first value. So, just do this:

    foreach ($array as $key => $value) {
        if (meetsCondition($value)) {
            $result = $value;
            break;
            // or: return $value; if in function
        }
    }
    

    array_filter will filter whole array. So if your required value is first, and array has 100 or more elements, array_filter will still check all these elements. So, do you really need 100 iterations instead of 1? The answer is clear - no.