How to Create a Calendar with PHP Code

Page content

Date Functions

One of the many interesting features of PHP are the date functions. These are of great help to anyone who wants to include a calendar on their website. Making a calendar is a relatively simple exercise, and is helped by the fact that PHP has the ability to represent days of the week in numbers. For this method Sunday is the first day – and is numbered as 0 – and Saturday the last and, of course, a number.

In order to make a calendar we need to know the present month and year, plus the day (or its corresponding number) that was the 1st of the month, and the day that will be the last. Those four, plus the number of days in the month, are the starting point.

Let’s have a look at the first sections of script:

Giving it a name

To start with, we name the calendar using the standard PHP scripts as follows:

The rules for creating rows and columns are as generally in php, and here’s how the script looks for the first two rows:

It is quite easy to follow once you know how, I’m sure you’ll agree.

Adding the blanks

Seeing as the month did not necessarily begin on the first day of the week, here’s the way – using the numerical day values – to put in the blank spaces at the beginning:

And to complete the row:

$count = 0;

for($j=1; $j < $numberOfDays; $j++)



echo “$j”;

if($count + $firstDayNumber ==7)

{echo “";break;} // end of if statement}

Now we have done one row, we can finish off the month, adding the spaces at the end thus:

$lastnumber = (7 - $lastDayNumber)- 1;

for($m=0; $m < $lastnumber; $m++)


echo “ ”;


The code above shows the fundamentals of creating rows for a PHP calendar. You must also remember that there are many different types of calendars, and many different ways of creating one for your website using PHP. Calendars can be just for a month, or a year, or for several years, and there are capabilities for doing all of these with PHP.