Dynamically Generate Months In PHP


Sometimes you may need to select month value from drop-down or select option box and for that you hardcode the month values in HTML option fields. It is possible to dynamically generate month values using PHP and you can use those generated month values in HTML select option tag. This way you do not need to hardcode the month values and easily generate months with a few line of code.

Related Post:


PHP 7.x, Apache HTTP Server (Optional)

Generate Months using PHP

Here is the example how you can generate month values in PHP technology. The following PHP code generates <select></select> and <option></option> tags.

<!DOCTYPE html>
        <meta charset="UTF-8">
        <title>Dynamically Generate Months in PHP</title>
        echo 'Usage Example<br/><br/>';
        echo 'echo generate_months();<br/><br/>';
        echo generate_months();

         * dynamically generate months dropdown
         * @param string $id id of the select-option
         * @return html
        function generate_months($id = 'month') {
            //start the select tag
            $html = '<select id="' . $id . '" name="' . $id . '">"n"';
            $html .= '<option value="">-- Month --</option>"n"';
            //echo each month as an option    
            for ($i = 1; $i <= 12; $i++) {
                $timestamp = mktime(0, 0, 0, $i);
                $label = date("F", $timestamp);
                $html .= '<option value="' . $i . '">' . $label . '</option>"n"';
            //close the select tag
            $html .= "</select>";

            return $html;

Testing Generated Months

Here is the output when you run the php-generate-months.php file in browser.

php generate months

In the above screen-shot, the function generate_months() generates 12 months from January to December.

Source Code


Leave a Reply

Your email address will not be published. Required fields are marked *