Fast Calendar Generator for PHP
August 2nd, 2007I’ve been using various calendar modules for years, and I’ve found most of them to be either resource intensive, obtuse to use, or just plain ugly code. Having yet another project that requires a calendar, I decided to finally build my own generator. This function simply builds an HTML table for the specified month. The only loops in the code are to actually generate the table. The rest of it uses PHP’s built-in array functions. It does not validate the input variables, either — that is done at the point the input is received.
<?php
function fast_calendar( $pYear = null, $pMonth = null ) {
$stamp = strtotime( $pYear . ‘-’ . $pMonth . ‘-01′ );
$grid = ( date( ‘w’, $stamp ) > 0 ) ? array_fill( 0, date( ‘w’, $stamp ), null ) : array();
$grid = array_merge( $grid, range( 1, date( ‘t’, $stamp ) ) );
$grid = ( count( $grid ) % 7 > 0 ) ? array_merge( $grid, array_fill( count( $grid ) - 1, 7 - ( count( $grid ) % 7 ), null ) ) : $grid;
$grid = array_chunk( $grid, 7, true );
$str = ‘<table border=”1″ cellpadding=”3″><tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>’;
foreach( $grid as $week => $days ) {
$str .= ‘<tr>’;
foreach( $days as $day => $label ) {
$str .= ‘<td height=”50″ width=”50″ valign=”top” align=”right”>’ . $label . ‘</td>’;
}
$str .= ‘</tr>’;
}
$str .= ‘</table>’;
return( $str );
}
?>




