Jump to content

[SOLVED] help with simple while loop - show current month name by number


scarhand

Recommended Posts

i am trying to generate a list of months with a simple while loop, but all i'm getting is 12 "December"'s in the select.

 

heres my code:

 

<?php

    <select name="birthmonth">
    <?php 
    $a = 1;
    
    while ($a <= 12)
    {
      $b = date("F", $a);
    
      if ($regbirthmonth == $b)
      {
        $selected = 'selected';
      }
      else
      {
        $selected = '';
      }
    
      echo "<option value=\"$b\" $selected>$b</option>";
      $a++;
    }
    ?>
    </select>

?>

 

any help would be greatly appreciated

    <select name="birthmonth">
    <?php 
    $a = 1;
    
    while ($a <= 12)
    {
      $b = date("F", mktime(0, 0, 0, $a, 1, 0));
    
      if ($regbirthmonth == $b)
      {
        $selected = 'selected';
      }
      else
      {
        $selected = '';
      }
    
      echo "<option value=\"$b\" $selected>$b</option>";
      $a++;
    }
    ?>
    </select>

 

Try that.

 

Edit: I also recommedn changing $selected = 'selected'; to $selected = 'selected=\"selected\"'; so that it is correct HTML encoding.

Just for fun, I'll throw this one in as another option:

<select name="birthmonth">
<?php
$m = 'January';
for ($i = 0; $i < 12; $i++)
{
  echo "<option name=\"$m\"";
  echo ($m == $regbirthmonth) ? ' selected="selected"' : '';
  echo ">$m</option>\n";
  $m = date('F', strtotime("$m + 1 month"));
}
?>
</select>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.