Php – for loop for each month of year


I want a loop that checks the current month, 12 months in the future and 4 months in the past.

For example: Today is 1st August 08. My loop should go through April, May, June, July, August, September, October, November, December, January, February, March, April, May, June, July, and August.

I have tried strotime but I don't know how I can loop 4 months back and 12 months in the future.

Here is my code

$i = 1; 
$month = strtotime('2013-08-01');

    while($i <= 12) {
        $month_name = date('F', $month);
        echo $month_name;
        echo "<br>";

        $month = strtotime('+1 month', $month);

Best Solution

I think Yoshi was almost there with his answer, but using DatePeriod with DateTime is more consistent and makes for more readable code IMHO:-

$oneMonth = new \DateInterval('P1M');
$startDate = \DateTime::createFromFormat('d H:i:s', '1 00:00:00')->sub(new \DateInterval('P4M'));
$period = new \DatePeriod($startDate, $oneMonth, 16);

foreach($period as $date){
    //$date is an instance of \DateTime. I'm just var_dumping it for illustration

See it working