What are some best practices for displaying a calendar with PHP, including handling date calculations and formatting?
When displaying a calendar with PHP, it's important to handle date calculations accurately and format the dates properly for readability. One way to achieve this is by using PHP's built-in date functions to generate the calendar grid and populate it with the correct dates. Additionally, consider using CSS to style the calendar for better visual presentation.
<?php
// Get the current month and year
$month = date('n');
$year = date('Y');
// Get the number of days in the current month
$days_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year);
// Get the first day of the month
$first_day = date('w', mktime(0, 0, 0, $month, 1, $year));
// Display the calendar grid
echo '<table>';
echo '<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>';
echo '<tr>';
// Display empty cells for the days before the first day of the month
for ($i = 0; $i < $first_day; $i++) {
echo '<td></td>';
}
// Display the days of the month
for ($day = 1; $day <= $days_in_month; $day++) {
echo '<td>' . $day . '</td>';
// Start a new row after Saturday
if (($first_day + $day) % 7 == 0) {
echo '</tr><tr>';
}
}
// Display empty cells for the days after the last day of the month
$last_day = date('w', mktime(0, 0, 0, $month, $days_in_month, $year));
for ($i = $last_day; $i < 6; $i++) {
echo '<td></td>';
}
echo '</tr>';
echo '</table>';
?>