Here's a well-documented PHP function that generates an array of strings in the format "month/year", where:
- Each entry is numeric (no leading zeros).
- The array starts from the current month.
- It goes backward for five years, including January of the year five years ago.
- The entries are ordered from most recent (current month) to oldest (January of the year five years ago).
✅ Function Definition
function generateMonths() {
// Create a DateTime object for the current date
$current = new DateTime();
// Calculate the end date: January 1st of the year five years ago
$end = new DateTime();
$end->setDate($current->format('Y') - 5, 1, 1);
$months = [];
// Loop while the current date is greater than or equal to the end date
while ($current >= $end) {
// Format the current month and year (e.g., "7/2023")
$months[] = $current->format('n/Y');
// Subtract one month
$current->modify('-1 month');
}
return $months;
}
📌 Example Output
If today is July 5, 2024, the output would be:
[
"7/2024",
"6/2024",
"5/2024",
"4/2024",
"3/2024",
"2/2024",
"1/2024",
"12/2023",
"11/2023",
"10/2023",
"9/2023",
"8/2023",
"7/2023",
"6/2023",
"5/2023",
"4/2023",
"3/2023",
"2/2023",
"1/2023",
"12/2022",
"11/2022",
"10/2022",
"9/2022",
"8/2022",
"7/2022",
"6/2022",
"5/2022",
"4/2022",
"3/2022",
"2/2022",
"1/2022",
"12/2021",
"11/2021",
"10/2021",
"9/2021",
"8/2021",
"7/2021",
"6/2021",
"5/2021",
"4/2021",
"3/2021",
"2/2021",
"1/2021",
"12/2020",
"11/2020",
"10/2020",
"9/2020",
"8/2020",
"7/2020",
"6/2020",
"5/2020",
"4/2020",
"3/2020",
"2/2020",
"1/2020"
]
This array contains 66 entries, covering from July 2024 back to January 2020, which is five years of data starting from the current month.
📝 Notes
- The
n format in DateTime::format() ensures that months are displayed without leading zeros (e.g., 7 instead of 07).
- The
Y format ensures that the full year is used (e.g., 2024 instead of 24).
- The loop correctly stops once the current date falls before the end date (January of the year five years ago), ensuring the array ends at that point.
✅ Usage Example
$monthList = generateMonths();
foreach ($monthList as $month) {
echo $month . PHP_EOL;
}
This will print each month in the desired format, starting from the current month and going back five years.