Better PHP Calendar Class

I've dealt with creating monthly calendars in PHP and it has always been a bit of pain. How exactly to show the days in the month in a table without creating ugly and hard to maintain code? I believe this time I was able to find a good solution.

A PHP Class

It's a PHP class that will output the dates of the given month in array. But in order to make the dates fit their place in the week, the class outputs zeros in the place of "empty" days. So the first week of a month starting in Wednesday would be this array:

[0, 0, 1, 2, 3, 4, 5]

This allows you to loop through the returned arrays without worrying where to start the week. If you use a table, you could simply output " " when the date is 0 and output the number (and colored background) when the date is a number. Here is an example in HTML:

Using the output in HTML:

    <?php for($i=1;$i<=$num_weeks;$i++):?>
            <?php $days=$_calendar->days($m[0], $m[1], $i, $num_weeks);
            foreach($days as $day):?>
            <?php endforeach;?>
    <?php endfor;?>

Easy, eh? We just output a table row for every week in the month ($num_weeks is also a method in the class as you'll see below) and for the days with date we output the date (otherwise just blank space).

You can see how it works live in this period calendar.

The PHP Code

Now, here is how it all works. I created a class to hold 3 functions:

num_weeks($month, $year) - to calculate the number of weeks in the given month and year

first_day($month, $year) - to find out which day of the week is the first day of a given month.year

days($month, $year, $week, $num_weeks=0) - this is the main method that returns the array of 7 days. The week starts in Monday.

Here is the full code below and some comments to it:

function num_weeks($month, $year)
        // every month has at least 4 weeks
        // finding where it starts
        $first_day = $this->first_day($month, $year);  
        // if the first week doesn't start on monday 
        // we are sure that the month has at minimum 5 weeks
        if($first_day!=1) $num_weeks++;
        // find the "widow" days (i.e. empty cells in the 1st week)
        if($fw_days==7) $fw_days=0;       
        // number of days in the month
        $numdays=date("t",mktime(2, 0, 0, $month, 1, $year));
        if( ($numdays - $fw_days) > 28 ) $num_weeks++;
         // that's it!
        return $num_weeks;                  

Then the first_day function:

function first_day($month, $year)
        $first_day= date("w", mktime(2, 0, 0, $month, 1, $year));
        if($first_day==0) $first_day=7; # convert Sunday
        return $first_day;

And here is the most important one:
// here $week is the week number when we go in a loop
// (see the html code that I posted earlier to get better idea)
function days($month, $year, $week, $num_weeks=0)

        // this is just to avoid calling num_weeks every time 
        // when you loop through the weeks        
        if($num_weeks==0) $num_weeks=$this->num_weeks($month, $year);
        // find which day of the week is 1st of the given month        
        $first_day = $this->first_day($month, $year);
        // find widow days (first week)
        // first week days
        // if $week==1 don't do further calculations
            for($i=0;$i<$widows;$i++) $days[]=0;            
            for($i=1;$i<=$fw_days;$i++) $days[]=$i;            
            return $days;
        // any other week
            for($i=$first+1;$i<=$first+7;$i++) $days[]=$i;            
            return $days;
        # only last week calculations below
        // number of days in the month
        $numdays=date("t",mktime(2, 0, 0, $month, 1, $year));
        // find orphan days (last week)  
        for($i=($numdays-$orphans)+1;$i<=$numdays;$i++) $days[]=$i;
        for($i=0;$i<$empty;$i++) $days[]=0;
        return $days;

That's it! Any questions?


  1. PHP is a very fast programming language for business. Thanks for sharing this information which is useful for all.

    php web development

  2. PHP is the best server side scripting language! I was is search of this php calender code ,thanks for sharing. I hope to see some more interesting php codes in this blog in near future.

    Ecommerce Design

  3. I was looking for the same calendar info for a long time thanks for sharing.

  4. It is great for beginner PHP learners.Thanks for all these information i hope to see more interesting and knowledgeable blog in near future.

  5. Find a php calendar here: http://bohemiawebsites.com/component/option,com_jdownloads/Itemid,382/cid,68/task,view.download/

    You can find more than 300 pages worth of php tutorials at http://bohemiawebsites.com/Our-Blog.html

  6. PHP contain the many class.but calender class provide the long time information.it also show the day and hours.actually its is great.

  7. Great Post for PHP learners..This is wonderful post. I do hope you intend to post more of these types of information. Thank you for this interesting information...
    Web Designing Company in Chandigarh

    1. EMC SAN Online Training is a best course all top company requires this,W3 D technology provides EMC SAN Online Training course with Certification and E-books , Videos
      EMC SAN Online Training | Storage Area Network Course

  8. I don't know how to use it to print calendar in HTML

  9. After make index.php file with HTML code from above, and then file calndar.class.php and put to the index.php code only calendar header with days show up... where are days?

  10. Very nice explanation on creating a calender.

    PHP Training in chennai

  11. Excellent post, for php developers, this class will allow you to add calendars in a variety of display types with only a few lines of code. Read more…

    Check this site Mindmajix for indepth PHP Tutorials

    Go here if you’re looking for information on PHP Blogs

  12. Nice blog...Very useful information is providing by ur blog. Great beginning php tutorials Very clear and helpful for beginners.

  13. Thank you for the informative post. Must appreciated.
    HTML5 Course in Velachery

  14. Thanks for sharing this wonderful information.Its very nice blog PHP

  15. Thanks for sharing great information in your blog. Got to learn new things from your Blog . It was very nice blog to learn about php

  16. thanks for giving this type of informative blog,we learn more things about tips for seo which is involves the detailed information about optimization of blogger.
    SAP Training in Chennai

  17. I have read your blog its very attractive and impressive. I like it your blog.

    PHP Training in chennai | PHP Training Course

    PHP Training in chennai | Online PHP Course

  18. EMC SAN Online Training is a best course all top company requires this,W3 D technology provides EMC SAN Online Training course with Certification and E-books , Videos
    EMC SAN Online Training | Storage Area Network Course

  19. Nice blog on php development. The information you are providing through this blog is very helpful to beginner Php Developers .


  20. My friend Suggest me this blog and I can say this is the best blog to get the basic knowledge.Thank you so much for this Selenium Training in Chennai

  21. Have you been thinking about the power sources and the tiles whom use blocks I wanted to thank you for this great read!! I definitely enjoyed every little bit of it and I have you bookmarked to check out the new stuff you post. java training jalandhar

  22. This is my first visit to your blog, your post made productive reading, thank you. dot net training in chennai


  23. This is best PHP tutorial in youtube. you can learn full coding and also the best expamles in here. This the best of learning and earning ways of youtube.
    You can the full boston php tutorial.

    click here PHP tutorial
    for more youtube tutorials
    website php tutorial for beginners

  24. Well explained. Got to learn new things from your Blog on Appium.Appium training in chennai

  25. Nice article
    Thanks for sharing the informative blog.

    ASP.NET Training In Bangalore

  26. You post explain everything in detail and it was very interesting to read. Thank you. nata coaching centres in chennai

  27. It's interesting that many of the bloggers your tips helped to clarify a few things for me as well as giving.. very specific nice content. And tell people specific ways to live their lives.Sometimes you just have to yell at people and give them a good shake to get your point across.
    Mobile App Development Company
    Android app Development Company
    ios app development Company
    Mobile App Development Companies

  28. Nice to read your article! very informative.So, please keep posting PHP Stuff here Thanks.......

  29. You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...
    PHP training in chennai

  30. Informative article, just what I was looking for.seo services chennai

  31. This blog explains the details of PHP. This helps to learn about what are all the different method is there. And the working methods all of that are explained here. Informative blog.For more Details Or information Visit Intellipaat

  32. Hi ,
    Nice article.Thank you for sharing the information.I really glad enjoy read that topic.I appreciate post for your.
    php Training in Chandigarh

  33. This blog is having the general information. Got a creative work and this is very different one.We have to develop our creativity mind.This blog helps for this. Thank you for this blog. This is very interesting and useful.
    PEGA Training in Chennai

  34. Its fantatic explaintion lot of information gather it...nice article....
    seo company in Chennai

  35. Great post! I am actually getting ready to across this information, It's very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    PEGA Training in Chennai

  36. Its a wonderful post and very helpful, thanks for all this information. You are including better information regarding this topic in an effective way.Thank you so much

    Installment Loans Near Me
    Title loans Near Me
    Cash Advances Near Me

  37. I feel happy to have Spent my time in reading such a useful blog.....
    SAP Training in Chennai

  38. Needed to compose one simple word yet thanks for the suggestions that you are contributed here, please do keep updating us...
    DevOps Training in Chennai | DevOps Online Training in Chennai

  39. Great post..thanks for sharing the valuable content..good work keep it up.
    Best software Training institute in Bangalore

  40. fantastic information! keep sharing.

  41. Thank you for sharing wonderful information with us to get some idea about that content. check it once through
    Machine Learning With TensorFlow Training and Course in Tel Aviv
    | CPHQ Online Training in Beirut. Get Certified Online

  42. Read all the information that i've given in above article. It'll give u the whole idea about it.

    DevOps Training in Bangalore

    DevOps Training in Pune

    DevOps Online Training

  43. Maka dari itu, dikesempatan ini admin akan memperkenalkan kepada anda beberapa Situs QQ Terbaru dan Terpercaya yang ada di Indonesia pada tahun 2019 – 2020 ini. Diantara para pembaca artikel ini, tentu saja mencari keberuntungan dengan bermain pada website baru.
    bandar ceme terbaik
    paito warna terlengkap
    syair sgp

  44. For Devops Training in Bangalore Visit: Devops Training in Bangalore

  45. Thanks for sharing information
    We are the best piping design course in Hyderabad, India. Sanjary academy Offers Piping Design Course and Best Piping Design Training Institute in Hyderabad. Piping Design Institute in India Piping Design Engineering.
    Piping Design Course
    Piping Design Course in india
    Piping Design Course in hyderabad

  46. Good Information
    Sanjary kids is the best playschool, preschool in Hyderabad, India. Start your play school,preschool in Hyderabad with sanjary kids. Sanjary kids provides programs like Play group,Nursery,Junior KG,Serior KG,and Teacher Training Program.
    play school in hyderabad, India
    Preschool in hyderabad, India
    Preschool teacher training course in hyderabad, India
    pre and primary teacher training course in hyderabad,India
    early childhood teacher training course in hyderabad, India

  47. Good information
    Best QA / QC Course in India, Hyderabad. sanjaryacademy is a well-known institute. We have offer professional Engineering Course like Piping Design Course, QA / QC Course,document Controller course,pressure Vessel Design Course, Welding Inspector Course, Quality Management Course, #Safety officer course.
    QA / QC Course
    QA / QC Course in india
    QA / QC Course in hyderabad

  48. Thanks for sharing such a wonderful content.
    We are the best waterproofing services in Hyderabad.We are providing all kinds of leakage services which includes bathroom,roof,wash area,water tank,wall cracks,kitchen leakage services in Hyderabad. With trust and honest, we solve the issue as quick as possible.We serve you better compared to others.
    Best waterproofing services in hyderabad
    bathroom leakage services in hyderabad
    roof leakage services in hyderabad
    water tank leakage services in hyderabad
    kitchen leakage services in hyderabad
    Hyderabad waterproofing services

  49. I have recently found an excellent Salesforce Training in India whose faculty is exceptional and you can also try this Salesforce Training and Certification in Jaipur whose syllabus is state of art. Here at Salesforce Training in Mumbai instructors are perfect to teach salesforce crm. My advice for you is to join demo at Salesforce training in Pune | Course Cost and in weekends try this best Salesforce Training in Noida | Course Cost who is providing great teaching services on Salesforce Training in Delhi and Fee Details.