<?php
// the month to render and day to highlight
$today = new DateTime();
// we'll need these to check if we're at the day we need to highlight
// or if we're rendering a date that's outside $today's month
$currentDay = $today->format('j');
$currentMonth = $today->format('n');
$daysInCurrentMonth = $today->format('t');
// figure out what Monday needs to kick off our table
$date = (clone $today)->modify('first day of this month');
if ($date->format('w') != 1) {
$date->modify('previous monday');
}
$shouldStopRendering = false;
echo '<table border="1">' . PHP_EOL;
while (!$shouldStopRendering) {
$weekDay = $date->format('w');
$month = $date->format('n');
$day = $date->format('j');
// start a new table row every time we hit a Monday, note that
// since we forced $date to be a Monday above, our table should
// now always start with a <tr>
if ($weekDay == 1) {
echo ' <tr>' . PHP_EOL;
}
if ($month != $currentMonth) {
// we're either at the beginning or end of our table
echo ' <td> </td>' . PHP_EOL;
} else if ($day == $currentDay) {
// highlight the current date
echo ' <td bgcolor="#ff0000">' . $day . '</td>' . PHP_EOL;
} else {
echo ' <td>' . $day . '</td>' . PHP_EOL;
}
if ($weekDay == 0) {
// every time we hit a Sunday, close the current table row
echo ' </tr>' . PHP_EOL;
// on a Sunday, if we've gone outside the current month **or**
// this Sunday happens to be the last day we need to render,
// stop looping so we can close the table
if ($month != $currentMonth || $day == $daysInCurrentMonth) {
$shouldStopRendering = true;
}
}
// move on to the next day we need to display
$date->modify('+1 day');
}
echo '</table>';