Here’s a good/efficient way of building a loop of years from a starting point to an ending point. For example, this code will show you how to print a range of years from 2000 to 2010:
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2002
2003
2004
2005
2006
2007
2008
2009
2010
The code is particularly useful if you want to create a dropdown for years. The example will output a list of years ranging from 1960 to the current year.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <? //year to start with $startdate = 1960; //year to end with - this is set to current year. You can change to specific year $enddate = date("Y"); $years = range ($startdate,$enddate); //print years foreach($years as $year) { echo $year . "<br />"; } ?> |
Update: Solution 2
I’ve just been messing around with some code, and I’ve figured out an alternative way of doing it, but with less code!
This code works kind of differently, but returns the same output (kind of). Unlike the previous solution, you don’t specify the start date, instead you specify how many years you want to go back from the current year. However, because you specify how many years you want to show, each time we’re into a new year, the oldest year will increase by 1 year. So if you go back 50 years, the date range will be 1960 – 2010. But next year (2011), the date range will be 1961 – 2011.
1 2 3 4 5 6 7 8 9 10 11 | //The 60 value here is the amount of years to go back $year = date("Y") - 50; //The 60 value here is the amount of years to go forward //because i went back 50 years, i'm going forward 50 years so the dropdown will always have the current year. for ($i = 0; $i <= 50; ++$i) { echo $year; //increase year counter by 1 ++$year; } |
Please let me know if you know of a better way to achieve the same output.
From the current year to 10 years in the future.
{
echo $year . '’;
}