Home > Software engineering >  Create Month And Year Dropdown Using PHP
Create Month And Year Dropdown Using PHP

Time:12-05

I am looking for dynamically generate Month And Year Dropdown Menu using PHP from Month December 2021 to December 2025. I need it like this

<select>
<option selected="" value="12-2021">December,2021</option>
<option value="1-2022">January,2022</option>
<option value="2-2022">February,2022</option>
<option value="3-2022">March,2022</option>
</select>

I have tried some codes like this

<select name="month" size='1'>
    <?php
    for ($i = 0; $i < 12; $i  ) {
        $time = strtotime(sprintf('%d months', $i));   
        $label = date('F', $time);   
        $value = date('n', $time);
        echo "<option value='$value'>$label</option>";
    }
    ?>
</select>

Its work for months but not able to combine it with years and values as per my requirements. I am new in PHP and not getting much idea how I can achieve it, Let me know if anyone here can help me for same. Thanks!

CodePudding user response:

<?php
    $start    = new DateTime('2021-12-01');
    $end      = new DateTime('2025-12-01');
    $interval = DateInterval::createFromDateString('1 month');
    $period   = new DatePeriod($start, $interval, $end);
?>

<select name="month" size='1'>
    <?php foreach ($period as $dt) 
         echo "<option value= " . $dt->format("Y-m") . ">" . strftime('%B-%Y', $dt->format('U')) . "</option>";
    ?>
</select>
  •  Tags:  
  • php
  • Related