dongzheng3113 2019-01-18 13:22
浏览 173
已采纳

数组的第一个元素[条件]

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:

  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?

</div>
  • 写回答

3条回答 默认 最新

  • dongnuo3749 2019-01-18 13:52
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看