Dynamically Generate Months In PHP

Introduction

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:

Prerequisites

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>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Dynamically Generate Months in PHP</title>
    </head>
    <body>
        <?php
        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;
        }
        ?>
    </body>
</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

Download

Leave a Reply

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