PHP 

Sometimes we need to select month value from drop-down and for that we hardcode the month values in HTML option fields. It is possible to dynamically generate the month values using PHP and we can use those generated month values in HTML select option tag.

You may also read Dynamically generate years in PHP

Here is the example how we can generate month values in PHP technology.

<!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>

Here is the output when we run the generate_month.php file in browser.

php generate months

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

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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