List year in the current year select to 10 years ago in descending order

Asked

Viewed 184 times

2

I am needing to list in a select the last 10 years. For this, I am doing so:

<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, ie from 2008 to 2018.

2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018

How do I make it countdown list? from 2018 to 2008?

2018
2017
2016
2015
....

2 answers

3

Just use the function rsort(), if you want 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>
  • 1

    The range is a more elegant solution. I hadn’t thought of it. :)

2


It’s not easier just to generate years backwards?

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.