Jump to content

[SOLVED] Load months into a option box


revraz

Recommended Posts

I was trying to come up with the best way to populate a option box and mark the current month as selected.  Can anyone shorten this or is this about as small as I can make it?

 

Requirement is that the value in the option must be 2 digits

 

<?php
$monthname = array ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$y=0; 				//set array index to 0
for ($x=1; $x <=12; $x++) { 	//set month to 1
printf("<option value=%02d", $x);  	//format option value to have leading 0 if less than 2
if (date('m', $todaydate)  == $x) echo " selected";  //if today, enter selected
echo ">" .$monthname[$y];		//display month name in the option list
$y += 1;				//increment array
echo "</option>";			//close options when done
?>

Link to comment
https://forums.phpfreaks.com/topic/83414-solved-load-months-into-a-option-box/
Share on other sites

<?php

$monthname = array ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

echo '<select name="month">';
foreach ($monthname as $id => $month) {
  echo '<option value="'.str_pad(($id+1),2,'0',STR_PAD_LEFT).'"'.((date('m',$todaydate)==($id+1))?' selected':'').'>'.$month.'</option>';
}
echo '</select>';

?>

Or this:

 

<?php

$monthname = array ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

echo '<select name="month">';
foreach ($monthname as $id => $month) {
  printf("<option value=\"%02d\"%s>%s</option>", ($id+1), ((date('m',$todaydate)==($id+1))?' selected':''), $month);
}
echo '</select>';

?>

You don't really need the array... you can use date() to populate everything you need.

 

<?php
$selected = '';
for ( $x=1; $x <= 12; $x++ ) {
   if ( date("n") == $x ) {
       $selected = ' selected';
   }
   echo "<option value=\"" . date("m", mktime(0, 0, 0, $x, 1)) . "\"$selected>" . date("F", mktime(0, 0, 0, $x, 1)) . "</option>\n";
    $selected = '';
}

 

Output:

 

<option value="01">January</option>
<option value="02">February</option>
<option value="03">March</option>
<option value="04">April</option>
<option value="05">May</option>
<option value="06">June</option>
<option value="07">July</option>
<option value="08">August</option>
<option value="09">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12" selected>December</option>

 

PhREEEk

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.