PHP loop through months array

PHP loop through months array

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Generating Month-Backed Select Dropdowns in PHP

Building a date picker or month selector often feels like overkill if you just need a simple <select> element driven by an array of months. The requirement to show eight months prior to the current one, inclusive, while defaulting to the current selection, is a common pattern in data entry forms. While it might seem straightforward at first glance, handling the date arithmetic and populating the options dynamically requires a specific approach to ensure accuracy regardless of whether the current month is June, January, or any other day.

The core logic involves iterating backwards from the current timestamp. You cannot rely on static strings like "June" or "November"; instead, you must generate the month names programmatically based on the current date context. This ensures that if a user visits your site in July, the default value automatically shifts without needing manual code changes. The most robust way to handle this is by leveraging PHP's DateTime class for calculations and IntlDateFormatter (or simple string arrays) for localization.

Here is a practical implementation using modern PHP features. First, we determine the starting point: the current month. We then loop backwards eight times to generate the range. The key challenge here is managing the default value. If you simply echo the options in a loop, you must check if the generated month matches the current one and set the selected attribute accordingly.

<?php
$current = new DateTime();
$start = (int)$current->format('n') - 8; // Calculate start index relative to current
$months = [];

// Loop backwards from current month minus 8 to current month
for ($i = $start; $i <= (int)$current->format('n'); $i++) {
    $date = new DateTime((string)$i . '-01', new DateTimeZone('UTC')); // Create a date for the first of that month
    $monthName = $date->format('F'); // Get full English month name (e.g., "June")
    
    // Determine if this is the current month to set as default
    $isSelected = ((int)$current->format('n')) === (int)$date->format('n') ? ' selected' : '';

    // You can also add a value attribute for form submission, e.g., "2023-06"
    $value = (string)$date->format('Y-m'); 

    echo "<option value=\"$value\"$monthName>$monthName</option>" . "\n";
}

One critical detail often overlooked is the handling of year boundaries. The prompt specifies that the range should go back even if it crosses into the previous year. In the code above, $i represents the month number (1–12), but we must ensure the DateTime object correctly interprets this within the context of the current year to avoid off-by-one errors or invalid dates. By initializing the DateTime object with a specific day (like the 1st) and the current timezone, PHP handles the leap years and varying month lengths automatically.

When integrating this into a larger application, you might want to bind these values directly to your form inputs rather than echoing raw HTML strings. This allows your framework or templating engine to handle the rendering safely. If you are using a framework like Laravel, you can pass an array of options to old_input or select helpers, provided you construct that array first using the same logic.

The trade-off here is performance versus flexibility. Generating this list on every page load is negligible for modern servers, but if you are generating thousands of months (e.g., for a decade-long history), caching the month names in a static array or constant might be worth considering. However, for an eight-month window, the overhead of calculating the current time is minimal and ensures your dropdown always reflects the actual date the user visits the site.

Finally, consider how you handle the form submission. If your backend expects a specific format like "2023-06" rather than just "June", ensure your value attribute matches that expectation. The visual label remains human-readable, but the underlying data must be machine-parseable. This separation of concerns—display vs. value—is a fundamental principle in building reliable web forms.

Our network