PHP Calendar

This utility function creates an HTML calendar table. Each day cell only contains the day number which may be a hyperlink. Example output:

Jul 2006
SunMonTueWedThuFriSat
1
2345678
9101112131415
16171819202122
23242526272829
3031

The CSS code for this particular style.

The PHP code:



/*
 * Draws a standard XHTML calendar with optional links for each day.
 *
 * Copyright (C) 2007 Clint Bellanger.  Released under the GPL.
 *
 * @param $year The 4-digit numeric year
 * @param $month The 2-digit numeric month.  1=Jan.
 * @param $day_links String array of hyperlink URIs indexed by day of month
 */
function display_calendar($year, $month, $day_links) {

  if ($month < 1 || $month > 12) return false;

  // setup
  $caption=jdmonthname(cal_to_jd(CAL_GREGORIAN,$month,1,$year),0) . " " . $year;
  $starting_day_of_week=jddayofweek(cal_to_jd(CAL_GREGORIAN,$month,1,$year),0);
  $days_in_month = cal_days_in_month(CAL_GREGORIAN,$month,$year);
  $day_of_week = 0; // 0=Sun through 6=Sat, keep track of our layout position

  // begin display
  echo "<table class=\"calendar\">\n";
  if ($caption != '') echo "  <caption>" . $caption . "</caption>\n";
  echo "  <tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th>"
    . "<th>Fri</th><th>Sat</th></tr>\n";

  echo "  <tr>";

  // if first day is not Sunday, skip empty spaces to reach correct position
  for ($skip=1;$skip<=$starting_day_of_week;$skip++) {
    echo "<td></td>";
    $day_of_week++;
  }
  
  for ($day=1; $day<=$days_in_month; $day++) {
    echo "<td>";

    // caller-specified link for this day
    if (isset($day_links[$day])) {
      echo "<a href=\"" . $day_links[$day] . "\">";
    }
    echo $day;
    if (isset($day_links[$day])) echo "</a>";

    echo "</td>";

    $day_of_week++;

    // if at a new sunday, start on the next week/row
    if ($day_of_week == 7) {
      $day_of_week = 0;
      echo "</tr>\n";
      if ($day < $days_in_month) echo "  <tr>";
    }
  }
  if ($day_of_week > 0) echo "</tr>\n";
  echo "</table>\n";

  return true;
} // end display_calendar()