Generate a menu with month names

I still see people building their calendar control or month (or day) picker with a hardcoded array of month (or day) names. With the use of strftime you can easily build a locale aware version. Here is an example:

<?php
function SelectMonths($name = 'selectMonths', $id = 'selectMonths') {
 $current_month = date('n');
  
 echo '<select name="' . $name .'" id="' . $id . '">';
 
 for ($i = 1; $i < 13; ++$i) {
  echo '<option value="' . $i . '"';

  if ($i == $current_month) {
   echo ' selected';
  }

 $month_name = strftime('%B', mktime(0, 0, 0, $i, 1, 2006));

  echo '>' . $month_name . '</option>';
 }
 
 echo '</select>';
}
?>

And now you can easily generate a localized menu:

<?php
include('SelectMonths.php');

SelectMonths();

// Tested on a Windows host - Read the http://be.php.net/setlocale
setlocale(LC_TIME, 'dutch');
SelectMonths();
?>

This entry was posted on Sunday, September 3rd, 2006 at 02:11 and is filed under PHP. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.