How to create a dinamic array of months: first element is the current month, the other elements are the following months

In this article I will show you how to create an array of months, where the first element is the current month, and the other elements are the following months.

This code is very useful when you need to handle events that have an expiration date.

<?php

	$months = array();
	$currentMonth = intval(date('m')); // get the current month number

	for($x = $currentMonth; $x < $currentMonth + 12; $x++) {
		$key = date('n', mktime(0, 0, 0, $x, 1));
		$value = date('F', mktime(0, 0, 0, $x, 1));

		$months[$key] = $value; // populate the associative array: $months( 6 => June, ... ) and so on
	}

	echo var_dump($months);  // print the array content
        
	/*
	array(12) { 
		[6]=> string(4) "June" 
		[7]=> string(4) "July" 
		[8]=> string(6) "August" 
		[9]=> string(9) "September" 
		[10]=> string(7) "October" 
		[11]=> string(8) "November" 
		[12]=> string(8) "December" 
		[1]=> string(7) "January" 
		[2]=> string(8) "February" 
		[3]=> string(5) "March" 
		[4]=> string(5) "April" 
		[5]=> string(3) "May" 
	}
	*/

?>

The mktime function, returns the unix timestamp corresponding to the arguments given: in our case hour, minute, second, month, day.
Take a look also to the date function, that return a string formatted using the given integer timestamp.

Tags:

Add new comment