meder omuraliev meder omuraliev - 5 months ago 45
PHP Question

PHP: Populating an array with the names of the next 12 months

for($x=0; $x<12; $x++)
$month = mktime(0, 0, 0, date("m")+$x, date("d"), date("Y"));
$key = date('m', $month);
$monthname = date('F', $month);
$months[$key] = $monthname;

I know for sure I'm doing the math incorrectly for the 4th parameter of mktime. I'm starting with the current month number ( 7 being July ) and adding 1 for each next month, sometimes it ends up being that the same month is returned twice, maybe because I'm not setting it to the beginning of the month? How would you improve/recode this?

Result is that $months would result in an array where 07 = July 08 = August, 09 = September. Right now it populates October twice. I think it has to do with today being the 31st and it incorrectly adds and reaches the next month.


Just fixed your code slightly, this should work pretty well:

$months = array();
$currentMonth = (int)date('m');

for ($x = $currentMonth; $x < $currentMonth + 12; $x++) {
    $months[] = date('F', mktime(0, 0, 0, $x, 1));

Note that I took out the array key, as I think it's unnecessary, but you can change that of course if you need it.