Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP PHP Arrays and Control Structures PHP Loops For Loops

Starting year not changing when changing increment operator

I have the following code:

<?php

$currentYear = date('Y');


for ($year = $currentYear - 100; $year <= $currentYear; ++$year) {
  echo $year . " \n";
}

?>

And the starting year is 1917 (it is 2017 at the time I write this). However I thought the operator ++$year is supposed to increment, and THEN return the value, meaning the starting year should be 1918, right?

Also, when I change the operator order to $year++, the starting date does not change. But I believe it should...

Thank you in advance.

  • C

1 Answer

Antonio De Rose
Antonio De Rose
20,882 Points
<?php
/*Loops work in the order of initialization, condition, statement, and then increment, 
just because, the condition comes in the same first line, it would not have any magical power,
for the increment to come first.*/


//the below is how a for loop works
for ($i = 0 /*(1) initialization*/; $i < 5 /*(2) condition*/; $i++ /*(4)increment*./) {
    // (3) do loop stuff
    /*(3)*/ print($i);
}

/*note -> however you address the increment, in the condition area ++$i, or $ii+, 
the result would be the same*/

//behind the scene this is what it is happening
for ($i = 0; $i < 5; ) {
    // do loop stuff
    print($i);

    $i++;
}

/*however if you want to still start from 2018 to print, you can work it out in the statement area
as below*/



$currentYear = date('Y');


for ($year = $currentYear - 100; $year <= $currentYear; ++$year) {
  echo ++$year . " \n";
}



?>