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

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,884 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";
}



?>