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

Link to comment
Share on other sites

    <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.

Link to comment
Share on other sites

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>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.