Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Print all the years dating back to when someone was born.

I have a form in html/php and that a user fills out. There is a field where they enter their age i.e. 22. I want to print all the years dating back to when that person was born. I've tried doing a loop but I get a bunch of numbers that have nothing to do with the age. Here is the equation below. The age is referred to with a variable; $age

for ($nYear = $age; $nYear <= date('Y'); $nYear++){ $yearsText .= $nYear . ' '; } $yearsText = trim($yearsText); echo $yearsText;

1 Answer

Kevin Korte
Kevin Korte
28,149 Points

Sure, so what its doing is taking the age number, like 22, and counting all the way up to the current year, 2016. So 22, 23, 24 ... 2014 2015 2016. That's the numbers it was putting out.

I refactored it, to what I think you want.

$age = 22;
$yearsText = "";
for ($nYear = date('Y') - $age; $nYear <= date('Y'); $nYear++){ 
  $yearsText .= $nYear . ' ';
}
$yearsText = trim($yearsText);
echo $yearsText;

So basically we start out setting $nYear to the year the person was born, doing this by taking the current year, 2016, and minus their age, 22, so we get the year 1994.

Now, our loop runs as long as $nYear is less than the current year.

So when you run this, you should get 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016

Which is I think what you wanted? The last thing to do is to make $age be set dynamically by your form, but that's easy.

I see now. Thank you so much!