List year in current year select for 10 years ago in descending order

2

I'm needing to list in a select the last 10 years. For this, I'm doing it this way:

<select name="AnoInicio" class="form-control">
  <option value="">Ano</option>
    <?php
       for ($anoInicio = date('Y') - 10; $anoInicio < date('Y'); $anoInicio++)
       {
          echo '<option value="'.$anoInicio.'">'.$anoInicio.'</option>';
       }
    ?>
</select>

It works, but the problem is that it is listing in ascending order, that is, from 2008 to 2018.

2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018

How do I make it count down? from 2018 to 2008?

2018
2017
2016
2015
....
    
asked by anonymous 18.12.2018 / 20:45

2 answers

2

Is not it easier just to generate years backwards?

<?php
$anoInicio = intval(date('Y'));
for ($i=0; $i < 10; $i++, $anoInicio--) {
    echo '<option value="'.$anoInicio.'">'.$anoInicio.'</option>';
}
    
18.12.2018 / 20:56
3

Just use the rsort() function, you can create an array with range() .

<?php
   $anoAtual = date('Y');
   $anos = range($anoAtual - 10, $anoAtual);
 ?>

<select name="AnoInicio" class="form-control">
<option value="">Ano</option>
<?php
   foreach($anos as $item) printf('<option value="%s">%s</option>', $item, $item);
 ?>
 </select>
    
18.12.2018 / 20:49