Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP loop through months array

Tags:

This should be easy but I'm having trouble...

In PHP how can I echo out a select drop down box that defaults to the current month and has options for 8 months prior (even if it goes in the last year).

For example, for this month it would default to June and end at November.

like image 228
kimion09 Avatar asked Jun 03 '11 00:06

kimion09


2 Answers

$months = array();
for ($i = 0; $i < 8; $i++) {
    $timestamp = mktime(0, 0, 0, date('n') - $i, 1);
    $months[date('n', $timestamp)] = date('F', $timestamp);
}

Alternative for "custom" month names:

$months = array(1 => 'Jan.', 2 => 'Feb.', 3 => 'Mar.', 4 => 'Apr.', 5 => 'May', 6 => 'Jun.', 7 => 'Jul.', 8 => 'Aug.', 9 => 'Sep.', 10 => 'Oct.', 11 => 'Nov.', 12 => 'Dec.');
$transposed = array_slice($months, date('n'), 12, true) + array_slice($months, 0, date('n'), true);
$last8 = array_reverse(array_slice($transposed, -8, 12, true), true);

To output an array of such months as dropdown is as simple as:

<select name="month">
    <?php
        foreach ($months as $num => $name) {
            printf('<option value="%u">%s</option>', $num, $name);
        }
    ?>
</select>
like image 62
deceze Avatar answered Nov 16 '22 11:11

deceze


If you need to print like select box options, try using this:

for($i=1;$i<13;$i++)
print("<option>".date('F',strtotime('01.'.$i.'.2001'))."</option>");
like image 21
Aleksandar Pavić Avatar answered Nov 16 '22 10:11

Aleksandar Pavić