Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

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

...