On a page I want to dynamically list years and all the months in each year so an archive for each month can be viewed. I want to show the current year first but the current year may not be over yet so I only want to show the months that have passed, and the current month. Then I want all years and all months in the past since this year (i.e. 2008).
The PHP code I have created that does the job is below. Is there a more efficient way of achieving this? I am running PHP 5.2.
$current_year = date('Y');
$months = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
// Loop through all the months and create an array up to and including the current month
foreach ($months as $month)
{
if ($month <= date('m'))
{
switch ($month)
{
case 1:
$years[$current_year][] = 'January';
break;
case 2:
$years[$current_year][] = 'February';
break;
case 3:
$years[$current_year][] = 'March';
break;
case 4:
$years[$current_year][] = 'April';
break;
case 5:
$years[$current_year][] = 'May';
break;
case 6:
$years[$current_year][] = 'June';
break;
case 7:
$years[$current_year][] = 'July';
break;
case 8:
$years[$current_year][] = 'August';
break;
case 9:
$years[$current_year][] = 'September';
break;
case 10:
$years[$current_year][] = 'October';
break;
case 11:
$years[$current_year][] = 'November';
break;
case 12:
$years[$current_year][] = 'December';
break;
}
}
}
// Previous years
$years_to_create = $current_year - 2008;
if (!empty($years_to_create))
{
for ($i = 1; $i <= $years_to_create; $i++)
{
$years[$current_year - $i] = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
}
}