1

I created a form that a user needs to fill out. Based on the age answer, I will need to list all years between the current year and the birth year. I was able to figure out how to convert the age number to an actual year with:

function birthday_year($years) {
    return date('Y', strtotime($years . ' years ago'));
}

$byear = birthday_year($age);
echo $byear;

I'm having a difficult time listing all the years between the birth year and current year. Any guidance would be appreciated. I was able to find other code examples that list months but when I try to manipulate the code to years it doesn't work at all. Only my 3rd week with PHP, so its still pretty new to me. Thanks!

Matthew Schmitt
  • 65
  • 1
  • 2
  • 9
  • Not sure why you marked it as duplicate. I mentioned in my post that I saw the months code examples but I need one for years and couldn't figure out how to change months to years – Matthew Schmitt Sep 25 '15 at 17:39

1 Answers1

9

There are several ways you could probably handle it, but a rather simple answer would be to loop from the year you've decided on, up to the current year.

for ($nYear = $byear; $nYear <= date('Y'); $nYear++) {
        echo $nYear . "\n";
}

Reverse the order :

for ($nYear = date('Y'); $nYear >= $byear; $nYear--) {
        echo $nYear . "\n";
}

Note that your code is wrong to assume that n years ago is the birth year. If you were 9 today (and your birthday was tomorrow) your code would say (today) that you were born in 2006 and tomorrow it would say 2005.

DragonYen
  • 958
  • 9
  • 22
  • Gotcha. Yeah, they don't input a day or month. They just pick their age number and I convert to a year. So, it works well for what I need. Would you know how to reverse the order of the results? So, instead of saying 1980 to 2015, is there away to have it output current year first(2015....1980)? – Matthew Schmitt Sep 25 '15 at 17:33
  • I've posted the reverse. You just initialize at the high end and count down instead. – DragonYen Sep 25 '15 at 17:40