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 PHP Arrays and Control Structures PHP Loops For Loops

Matt Fried
Matt Fried
10,665 Points

Starting year is incremented prior to executing for loop

In the following code:

<?php
$currentYear = date('Y');

for ($year = $currentYear - 100;$year <= $currentYear;$year += 1) {
  echo $year . "<br />\n";
}
?>

the output starts with 1919 (it is 2018 at this time), but I don't understand why it isn't starting with 1918??

1 Answer

Matthew Lang
Matthew Lang
13,483 Points

Hi.

I've tested your code in a REPL (Read-Eval-Print-Loop) environment for PHP, and the first output was in-fact 1918. I'm not sure where you're going wrong. Here is the REPL I'm talking about: https://repl.it/repls/YoungVengefulSequel

You can use this tool/website to test loose bits of PHP, it can be very helpful. I hope this helps.

Your problem must be to do with something else, perhaps you could show us all of the code? Thank you.

Matt Fried
Matt Fried
10,665 Points

Thanks Matthew for checking this out. You're right, it must be something else.

I've come to the conclusion that the issue is Google Chrome, which seems to be hiding the first year output '1918' with whitespace or something like that. It outputs fine with Safari. In order to get it to work with Google Chrome, I had to change the echo statement as shown below, and now '1918' appears in my output.

<?php
$currentYear = date('Y');

for ($year = $currentYear - 100;$year <= $currentYear;$year += 1) {
  echo "<p>$year</p>";
}
?>