First element of array by condition [duplicate]

半世苍凉 提交于 2020-03-22 11:05:30

问题


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?


回答1:


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; in 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.




回答2:


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.




回答3:


Your array :

$array = [
['value' => 100, 'tag' => 'a'],
['value' => 200, 'tag' => 'b'],
['value' => 300, 'tag' => 'a'], 
];

To find the entries via conditions, you could do this

$newArray = array_values(array_filter($array, function($n){ return $n['value'] >= 101 && $n['value'] <= 400; }));

With this you can set to values, min and max numbers.

if you only want to set a min number, you can omit the max like this

$arrayByOnlyMin = array_values(array_filter($array, function($n){ return $n['value'] >= 199; }));

This would return :

 array(2) {
 [0]=>
    array(2) {
      ["value"]=>
      int(200)
      ["tag"]=>
      string(1) "b"
    }
 [1]=>
   array(2) {
      ["value"]=>
      int(300)
      ["tag"]=>
      string(1) "a"
    }
}

so calling $arrayByOnlyMin[0] would give you the first entry, that matches your min condition.



来源:https://stackoverflow.com/questions/54254926/first-element-of-array-by-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!