PHP: Convert number to month name.

This is a short guide on how to convert an integer number into a month name using PHP.

Let’s jump right into a code example:

A drilldown of the PHP snippet above:

  1. In this tutorial, we are receiving the numerical value of the month from a GET parameter. Because it is coming from an external source, we will need to validate the number and make sure that it falls between 1 (January) and 12 (December). We have to validate it because you can never ever trust data that is coming from an external source. i.e. We do not want somebody giving us a month number of 1000 or -2.
  2. We create a variable called $text. By default, we set it to “Invalid Month”. If the month is valid, this text will be overwritten.
  3. We use an IF statement to make sure that it is a valid month number that falls between 1 and 12.
  4. If it is a valid number, we use PHP’s date function to get the full textual representation of the month in question. In this case, we are using the “F” format character. For the second parameter, we pass in a date that contains the month number (YYYY-MM-DD format). If the $month variable is 2, then the date will be 2001-02-01. Note that the year and day segments of the date do not matter, as we are only interested in the “F” format character.
  5. Finally, we print out the full name of the month.

As you can see, it is pretty straight-forward!

Facebook Comments