Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First element of array by condition [duplicate]

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?

like image 939
simon.ro Avatar asked Jan 18 '19 13:01

simon.ro


People also ask

How do you find the first duplicate element in an array?

Copy the given array to an auxiliary array temp[]. Sort the temp array using a O(nLogn) time sorting algorithm. Scan the input array from left to right. For every element, count its occurrences in temp[] using binary search.

How do you check if an array contains the same value?

To check if all values in an array are equal: Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.


2 Answers

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.

like image 51
wilsonzlin Avatar answered Oct 10 '22 16:10

wilsonzlin


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 asnwer is clear - no.

like image 41
u_mulder Avatar answered Oct 10 '22 16:10

u_mulder