LoginSignup
5
2

More than 5 years have passed since last update.

PHPで times というヘルパー関数を作ったら意外と便利だった

Last updated at Posted at 2017-09-21

概要

  • Ruby でいう 5.times { puts 'Hello' }
  • JS の lodash でいう _.times(5, () => console.log('Hello'))

がPHPでもやりたい。が、普通にやろうとすると

foreach (range(1, 5) as $i) {
    echo "Hello\n";
}

となるが、単純に繰り返したい場合は $i が不要なのに、変数として付けないといけない。名前空間を汚染されて困る。
また未使用の変数としてLinterに怒られるのもつらい。

そこで

定義した。

function times($times, \Closure $callback)
{
    $range = range(1, $times);
    foreach ($range as $i) {
        $callback($i);
    }
    unset($i);
}

使い方は

times(5, function () { 
    echo 'Hello'."\n"; 
});

現在の繰り返し回数を知りたい場合は

times(5, function ($i) { 
    echo 'Hello, '.$i."\n"; 
});

[追記]

@unulk さんにコメントでご指摘頂いた通り、Laravelにあった。5.4から使えるようです。

ただしこれは Collection オブジェクトを新しく生成するので、ただ単に繰り返すだけであれば高コストか。

また、 @jkr_2255 さんにご指摘頂いた通り、引数のタイプヒントは、 callable の方が良さそう。
上述のLaravelのコードでもそうなっている。

function times($times, callable $callback)

これなら、関数の名前だけ渡すとかできるので。

所感

Laravelにありそうで無いヘルパー関数な気がする。

5
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2