简体   繁体   中英

How to use for-loop for values in descending order

I am showing a list of years in a dropdown box. The years range from 2017 to the current year. Currently, the values are shown in my dropdown starting from 2017 and increasing up to the current year. But I want the values to be shown in descending order, with the current year (2019) on top, then 2018, and finally 2017.

Here is my current code:

<?php
for ($i=2017; $i < date("Y")+1; $i++) { 
?>
  <option value="<?php echo$i?>" <?php if($_POST['master_year']== $i) {echo 'selected';} ?>><?= $i;?></option>
<?php 
}
?>

How can I change this to show them in descending order?

Simply change the order of your for loop. You initialize $i at 2017 to start. Then, you end it when it is equal to date("Y"). You add 1 to it each loop. Reverse all of that:

for($i = date('Y'); $i >= 2017; $i--)

This is not unique to PHP. This is the basic construct of a for loop. If you are having trouble with it, PLEASE do not develop anything critical. Take time to learn the basics of control structures in programming first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM