Adam
Adam

Reputation: 9449

PHP Looping through months for blog archive

I'm trying to create a list of the years with the months from today until the oldest record in the database. It's working great, except that the loop stops before it gets to the oldest month. Here's my code:

echo $oldest_entry; //2012-01-31
$end = strtotime($oldest_entry);
$month = strtotime(date('Y-m-d'));
$year = "";
while($month >= $end)
{
     if(date('Y', $month) != $year){ 
        echo "<b>".date('Y', $month)."</b><br/>";
        $year = date('Y', $month); 
     }
     echo date('F', $month)."<br/>";
     $month = strtotime("-1 month", $month);
}

It outputs: 2012

March

February

And doesn't get to January. What am I doing wrong here? I thought adding the = to the > would fix this but it didn't.

Upvotes: 0

Views: 607

Answers (1)

Mark Byers
Mark Byers

Reputation: 838106

It doesn't print January because 2012-01-16 >= 2012-01-31 is false.

You should omit the date. Use only the year and the month in your comparison.

Upvotes: 4

Related Questions