Reputation: 1520
How to get an for loop
to show the last 4 years?
When I use for($z = date("Y"); $z <= date("Y") + 3; $z++)
I am getting: 2020 & 2021 & 2022 & 2023.
But I need (in this order) 2020 & 2019 & 2018 & 2017.
I have tried for($z = date("Y"); $z <= date("Y") - 3; $z-1)
but that gives no result. Any suggestions?
Upvotes: 1
Views: 111
Reputation: 17805
You are looping forward, but you need to loop backwards. So,
for($z = date("Y"); $z <= date("Y") + 3; $z++)
Should be,
for($z = date("Y"); $z >= date("Y") - 3; $z--)
Demo: https://3v4l.org/WC4MQ
You can also use a range
function to get a range of year values.
<?php
$current_year = date("Y");
print_r(range($current_year,$current_year-3));
Demo: https://3v4l.org/VTKoH
Upvotes: 4