How to draw a calendar for a specific year and month in PHP and HTML

1 Answer

0 votes
<!DOCTYPE html>
<html>
<body>
<?php
function draw_calendar($month, $year) {
    // First day of the month
    $first_day = mktime(0, 0, 0, $month, 1, $year);
    // Number of days in the month
    $days_in_month = date('t', $first_day);
    // Day of the week the month starts on
    $day_of_week = date('w', $first_day);

    // Calendar header
    $calendar = "<table border='0'>";
    $calendar .= "<tr><th colspan='7'>" . date('F Y', $first_day) . "</th></tr>";
    $calendar .= "<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr><tr>";

    // Fill the first row with empty cells if the month doesn't start on Sunday
    if ($day_of_week > 0) {
        $calendar .= str_repeat('<td></td>', $day_of_week);
    }

    // Fill the calendar with days
    $current_day = 1;
    while ($current_day <= $days_in_month) {
        // Start a new row every Sunday
        if ($day_of_week == 7) {
            $day_of_week = 0;
            $calendar .= "</tr><tr>";
        }

        $calendar .= "<td>$current_day</td>";
        $current_day++;
        $day_of_week++;
    }

    // Fill the last row with empty cells if the month doesn't end on Saturday
    if ($day_of_week != 7) {
        $calendar .= str_repeat('<td></td>', 7 - $day_of_week);
    }

    $calendar .= "</tr></table>";
    return $calendar;
}

echo draw_calendar(2, 2025);
?>
</body>
</html>



answered Feb 19, 2025 by avibootz
edited Feb 19, 2025 by avibootz

Related questions

...