LoginSignup
8

More than 5 years have passed since last update.

DatePeriodでハマる人がいるらしいので、for文で説明してみた

Posted at

PHPで日付をループする方法と罠のように、プログラミング初心者にはハマりやすい罠らしいです。for文で書き直してみたら多分そんなくだらないハマり方しなくなると思うので、書いておきますね。

コードは、上記の記事のやつを勝手に拝借して、適当に修正してます。

<?php
$start = new DateTime('2016-11-02');
$end = new DateTime('2016-11-08');
$interval = new DateInterval('P2D');

$period = new DatePeriod($start, $interval, $end);

foreach ($period as $date) {
    echo $date->format('Y-m-d').PHP_EOL;
    // $end の "2016-11-08" は出力されない
}

これを for文 で書くと、こんな感じになります。

<?php
$start = new DateTime('2016-11-02');
$end = new DateTime('2016-11-08');
$interval = new DateInterval('P2D');

for ($currentDate = $start; $currentDate < $end; $currentDate->add($interval)){
    echo $currentDate->format('Y-m-d').PHP_EOL;
    // $end が出力されない!!!><
}

$current < $end; って書いてるのに、$endが含まれるわけねーじゃんwww 」と、すぐに気付けます。一目瞭然ですね。

「for文の文2は <= を使うだろ常考www」っていうツッコミを受けそうな気がしましたが、範囲を表す場合は「包含-排他範囲」が基本です。
DatePeriod::__constructの第3引数は$endなので、$end自身を含めないのが一般的な解釈でしょう。

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
8