Month Names in PHP

One simple thing I keep having to do over and over again is to display the name of the month for a given date. Normally I have opted to use the first solution that comes to mind which is creating an array with all the month names in it and then when I want to retrieve the month name I just use

$monthName = $aMonth[$monthNum];

However, when I wanted to use PHP to display the month name this time I wanted to see if there was a better solution.

The one I came across was posted on The Code Cookbook and was a simple 1 line statement which was great… simpler, neater and far more elegant than my usual method and it looked like

$monthName = date(“F”, mktime(0, 0, 0, $monthNum, 10));

Normally I would have been happy with this, however was needing to deal with a month drop down box which didn’t run from January to December but instead ran from November to April but this worked out to be rather simple too.

Using PHP to display the month names from November to April was achieved simply by using the above statement in a loop and my first attempt looked like this:-

for($i=0;$i<6;$i++) {
echo date(“F”, mktime(0, 0, 0, (($i+11) % 12), 10));

As I was aware the months would be rolling over to the following year I have attempted to use the mod function to ensure the month values are valid. The numbers for months, unlike days and years, run from 0 to 11 representing January to December respectively so the above loop works great, however it can be simplified yet again.

After one of my colleagues looked over this section of code they advised me that mktime will automatically round the date should you attempt to create an invalid date so the above loop can be simplifed to:-

for($i=0;$i<6;$i++) {
echo date(“F”, mktime(0, 0, 0, $i+11, 10));

What I was expecting was:-

2009-11-01 = OK
2009-12-01 = OK
2009-13-01 = NOT OK

but instead the last of those 3 examples actually gave the value of 2010-01-01 which is a valid date and would mean that I would be able to display the month names November to April very very easily indeed!

Now that I’m aware of that I’ll not be going back to my old method for display month names in PHP!

Author : Christopher Shennan


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: