[thelist] Automatic calendar in a table script - revisited in PHP

Nicole Parrot nicole at parrot.ca
Tue Jan 15 22:20:34 CST 2002


Last week, .jeff published his algorithm to create a calendar using only one
loop.
Turns out I needed something like that for another project, but not in Cold
Fusion. So I translated it to PHP. I'm interested in "code reviews" from PHP
knowledgeable people, cause I translated from a language I have never seen
before to a language I've just started learning. It does work, though!
;-)

Here's the PHP code, if anyone is interested. No strings attached.
There's one noticeable change to the algorithm that .jeff published. His was
meant to have an equal number of rows for each month, regardless of the
number of days in the month, so they would look side by side. Since I'm only
drawing one month at a time, the potential extra row looked weird, so it got
removed.

<?php

function DayOfWeek($month,$year)
{
$firstofthemonth = strtotime("$month/01/$year");
$firstofthemonthArray = getdate($firstofthemonth);
$startday = $firstofthemonthArray['wday'];
return $startday;
}

function DaysInMonth($month, $year)
{
 for ($i = 31; $i > 0; $i--) {
  if (checkdate($month, $i, $year)) {
   return $i;
  }
 }
 return 0;
}

function DrawCalendar($month, $year)
{
 $DateArray = getdate(strtotime("$month/01/$year"));

 echo ("<table border=1> \n");
 echo ("<tr><td colspan=\"7\" align=\"center\">\n");
 echo $DateArray['month']." ".$year;
 echo ("</td></tr>\n");
 echo ("<tr>");
 echo ("<td width=\"15%\" align=\"center\">Sunday</td>");
 echo ("<td width=\"14%\" align=\"center\">Monday</td>");
 echo ("<td width=\"14%\" align=\"center\">Tuesday</td>");
 echo ("<td width=\"14%\" align=\"center\">Wednesday</td>");
 echo ("<td width=\"14%\" align=\"center\">Thursday</td>");
 echo ("<td width=\"14%\" align=\"center\">Friday</td>");
 echo ("<td width=\"15%\" align=\"center\">Saturday</td>");
 echo ("</tr>\n");

  $dayofweek = DayOfWeek($month, $year);
  $daysinmonth = DaysInMonth($month, $year);
  $lastcell = ( ceil(($daysinmonth + $dayofweek) / 7 )*7 );
  for($i = 0; $i < $lastcell; $i = $i + 1)
  {
    if( $i % 7 == 0)
      echo ("<tr>\n");
    if($i < $dayofweek OR $i > $daysinmonth + $dayofweek -1)
      echo ( "<td>&nbsp;</td>\n");
    else
    {
      $date = $i - $dayofweek +1;
      echo("<td>$date</td>\n");
    }
    if( (($i+1)%7) == 0)
        echo("</tr>");
 }
  echo ("</table>\n");
}

// this will draw the whole 2002 year as a proof that it works .
for ($i = 1; $i <=12; $i++)
{
 DrawCalendar($i,2002);
 echo "<br />\n\n";
}
?>





More information about the thelist mailing list