dougu5950 2016-08-10 17:04
浏览 28
已采纳

too long

I'm curious if there's a better way to do what I'm doing. I'm fairly new to php so I'm interested in what others think who have spent more time with the language.

What I want to do: call a function on every object in an array

What I'm doing:

array_map(function($object) { $object->loadEvents(); }, $patients);

This is fine, and it works. I could also use a for loop,

Why I'm asking: I've become accustomed to not using for loops when I don't have too, so I figured out a way to use array_map. The thing is, every where I look, it seems people are using array_map to map results to a new array. When I basically want the functionality of array_map but without the return values.

Is there a better way? Outside this and a for loop? Is a for loop a better way?

  • 写回答

2条回答 默认 最新

  • douzhi1813 2016-08-10 17:12
    关注

    The usual idiom in PHP for looping over an array is the foreach operator. array_walk and array_map can be used, but they didn't become common idioms because until relatively recent versions of PHP creating anonymous functions was inconvenient. Prior to PHP 5.3, you had to call create_function() to create a function on the fly. So array_walk and array_map were usually only used when there's a named function that does what you want, e.g.

    $array = array_map('trim', $array);
    

    But even now that you can use function to create anonymous functions, many people find

    array_walk($array, function($x) {
        ...
    });
    

    less readable than

    foreach ($array as $xx) {
        ...
    }
    

    array_map tends to be used more than array_walk because it can be used as part of a larger expression. With foreach you would have to use one loop to push onto a result array, then follow it with code to operate on that array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大