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\', $mo
"Result is that $months would result in an array where 07 = July 08 = August, 09 = September."
for ($key = 1; $key <=12; $key++) {
$months[str_pad($key, 2, '0', STR_PAD_LEFT)] = date('F', strtotime('2000-' . $key));
}
If you're okay with 7 = July 8 = August, 9 = September, then:
for ($key = 1; $key <=12; $key++) {
$months[$key] = date('F', strtotime('2000-' . $key));
}
Less complicated, no loops, generic array keys:
function stackoverflow_get_monthname($x){
return date("F",mktime(NULL, NULL, NULL, (int)date("n") + ($x+1), NULL, NULL));
}
$months = array_map("stackoverflow_get_monthname", range(1,12) );
var_dump($months);
Given 2592000 is 30 days.
$month_time = 60*60*24*30; // 30 Days
for($x=0; x<12; $x++)
{
$time = time()+($month_time*$x);
$key = date('m', $time);
$month[$key] = date('F', $time);
}
In an answer on StackOverflow, can't find it right now, someone compared the performance of multiple methods of creating a time 1 week from now. Directly using numbers was much more efficient than any other method.
An alternative would be to use strtotime:
for ($x=0; $x < 12; $x++) {
$time = strtotime('+' . $x . ' months', strtotime(date('Y-M' . '-01')));
$key = date('m', $time);
$name = date('F', $time);
$months[$key] = $name;
}
In my opinion this code is easier to read.
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.
Here is a simple script to go forward 12 months from the current date. It includes the year with it.
# Set Number of Months to Traverse
$num_months = 12;
# Set Current Month as the 1st
$current_month = date('Y-m').'-01';
for ($count = 0; $count <= $num_months; $count++) {
# Fetch Date for each as YYYY-MM-01
$dates[] = date('Y-m', strtotime($current_month.' + '.$count.' Months')).'-01';
}
You could turn this into a select list with the current month selected by dropping this in:
echo '<select name="month">';
foreach ($dates as $d) {
echo '<option value="'.$d.'"';
if ($d == date('Y-m').'-01') echo 'selected="selected"';
echo '>'.date('F, Y', strtotime($d)).'</option>';
}
echo '</select>';