This is a short guide on how to convert an integer number into its equivalent month name using PHP.
Let’s jump straight into a code example:
//In this example, we're getting the numerical //value of our month from a GET variable. $month = intval($_GET['month']); //By default, we set it to "Invalid Month" $text = 'Invalid Month'; //The $month must be between 1 (January) and 12 (December). if($month >= 1 && $month <= 12){ //The month is valid. //Get the textual representation. $text = date("F", strtotime("2001-" . $month . "-01")); } //Print the textual representation of our month //out onto the page. echo $text;
A drilldown of the PHP snippet above:
- 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 trust data that comes from an external source. In other words, we do not want someone giving us a month number of 1000 or -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.
- We use an IF statement to make sure that the integer value is a valid month number that falls between 1 and 12.
- 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.
- Finally, we print out the full name of the month.
As you can see, it is pretty straightforward.