每个月的每个月的循环

I am trying to write a for loop in PHP to add to an HTML <select> tag dropdown, that allows people to pick their birth month.

Heres my code which isn't working:

            <p>
            <label for="signup_birth_month">Birthday:</label>
            <select name="signup_birth_month" id="signup_birth_month">
            <option value="">Select Month</option>
            <?php

            for ($i = 1; $i <= 12; $i++)
            {
                $month_name = date('F', mktime(0, 0, 0, $i, 1, 2011));
                echo '<option value="'.$month_name.'"'.$month_name.'></option>';
            }

            ?>
            </select>
            </p>

How do I write a for loop that returns the name of each month in year?

You need to quote the value key with:

echo "<option value=\"" . $month_name . "\">" . $month_name . "</option>";

In addition, I'd probably prefer something like this:

$months = array("Jan", "Feb", "Mar", ..., "Dec");
foreach ($months as $month) {
    echo "<option value=\"" . $month . "\">" . $month . "</option>";
}

It seems bizarre that you would make all those unnecessary calls to date and mktime when you know what the values should be.

This array version has the same number of lines and it seems a lot clearer in intent (at least to me).

Are you not seeing the month name get printed in the select box?

I think this should do the trick:

echo "<option value=\"" . $month_name . "\">" . $month_name . "</option>";

I think you should fix the HTML part.

echo '<option value="'.$month_name.'">'.$month_name.'</option>';

Dont forget to set the default timezone before

date_default_timezone_set('Your/Timezone');

Or else you will get a E_WARNING for date() and mktime() (if you set error_reporting(E_ALL)). Take a look at http://www.php.net/manual/en/timezones.php for valid timezones.

Alternatively, you could also use something like

$i = 1;
$month = strtotime('2011-01-01');
while($i <= 12)
{
    $month_name = date('F', $month);
    echo '<option value="'. $month_name. '">'.$month_name.'</option>';
    $month = strtotime('+1 month', $month);
    $i++;
}

But the for loop is just fine.

for($iM =1;$iM<=12;$iM++){
echo date("M", strtotime("$iM/12/10"));}

Very simple!

function getLocalMonthName($locale, $monthnum)
{
    setlocale (LC_ALL, $locale.".UTF-8");
    return ucfirst(strftime('%B', mktime(0, 0, 0, $monthnum, 1)));
}

print getLocalMonthName("pt_BR", 1); // returns Janeiro

Very simple solution:

print '<option value="" disabled selected>Select month</option>';
for ( $i = 1; $i <= 12; $i ++ ) { 
    print '<option value="' . $i . '">' . date( 'F', strtotime( "$i/12/10" ) ) . '</option>'; 
}

PHP code to print out the name of each month:

<?php 
date_default_timezone_set('America/New_York'); 
for($i=1; $i<=12; $i++){ 
    $month = date('F', mktime(0, 0, 0, $i, 10)); 
    echo $month . ","; 
    // It will print: January,February,.............December,
}
?>