Search code examples
phphtmlforms

Limit Month and Year with Select Input in PHP


I am trying to automate form, a select input with limited month and year in PHP. I can't find or create an algorithm to skip months starting from today's month.

Here is what I desired, https://codepen.io/abdullah1929/pen/XWoQNBL

This is what I've tried,

<?php
ini_set('default_charset', 'UTF-8'); // for some name like Ibañez, Nuñez
date_default_timezone_set('Asia/Singapore');
$start = 2014;
$end = intval(date('Y', time()));
$month = intval(date('m', time()));

?>
<select name="month">

<?php
    for($i = $end; $i >= $start; $i--){

        if($month < (ceil($month/12)+1)){
            continue;
        }
    ?>
    <!-- <option value="december2023">December 2023</option>
    <option value="november2023">November 2023</option>
    <option value="october2023">October 2023</option>-->
        <option value="december<?=$i?>">December <?=$i?></option>
        <option value="november<?=$i?>">November <?=$i?></option>
        <option value="october<?=$i?>">October <?=$i?></option>
        <option value="september<?=$i?>">September <?=$i?></option>
        <option value="august<?=$i?>">August <?=$i?></option>
        <option value="july<?=$i?>">July <?=$i?></option>
        <option value="june<?=$i?>">June <?=$i?></option>
        <option value="may<?=$i?>">May <?=$i?></option>
        <option value="april<?=$i?>">April <?=$i?></option>
        <option value="march<?=$i?>">March <?=$i?></option>
        <option value="february<?=$i?>">February <?=$i?></option>
        <option value="january<?=$i?>">January <?=$i?></option>
    <?php } ?>
</select>

I am struggling here for hours now. Thanks for the help.


Solution

  • Use two loops. The first loop is for all years after the current year, it should print all months in the year.

    The second loop is for the current year, it should stop when it gets to the current month.

    <?php
    ini_set('default_charset', 'UTF-8'); // for some name like Ibañez, Nuñez
    date_default_timezone_set('Asia/Singapore');
    $start = 2014;
    $end = intval(date('Y', time()));
    $month = intval(date('m', time()));
    
    ?>
    <select name="month">
    
    <?php
        $months = ['december', 'november', 'october', 'september', 'august', 'july', 'june', 'may', 'april', 'march', 'february', 'january'];
        // later years
        for($y = $end; $y > $start; $y--){
            foreach ($months as $m) { ?>
                <option value="<?= $m.$y ?>"><?= ucfirst($m) . " " . $y ?></option>
                <?php
            }
        }
        // current year
        for ($mnum = 12; $mnum >= $month; $mnum--) { ?>
            <option value="<?= $months[$mnum].$start ?>"><?= ucfirst($months[$mnum]) . " " . $start ?></option>
            <?php
        } ?>
    </select>