Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php increment a value

Tags:

php

while-loop

I have set to constants, a start year and an end year,
so i have built a while loop on the condition that

if the start year is < than the current year increment until true.

the problem i have is that instead of it going up like this:

1999,2000,2001,2002,2003,2004

it goes like:

1999,2001,2003,2005,2007,2009

Here is my code:

function yearCount()
{
  $yearBegin = START_YEAR;
  $yearCurrent = CURRENT_YEAR;
  while($yearBegin < $yearCurrent){
    echo "<option value=\"".$yearBegin++."\">".$yearBegin++."</option>";
  }
}

any ideas would be highly appreciated.

like image 820
Adamski Avatar asked Nov 22 '25 09:11

Adamski


2 Answers

You are incrementing the value twice:

echo "<option value=\"".$yearBegin++."\">".$yearBegin++."</option>";

Each $yearBegin++ increments it by one.

Use a for loop instead:

for ($yearBegin = START_YEAR; $yearBegin < CURRENT_YEAR; $yearBegin++)
{
  echo "<option value=\"".$yearBegin."\">".$yearBegin."</option>";
}
like image 196
Femaref Avatar answered Nov 24 '25 23:11

Femaref


Using a for loop is usually the way to do this,

for($year=START_YEAR;$year<=CURRENT_YEAR;$year++)
{
    //User the $year here
}

your problem with the code is that your calling $yearBegin++ 2 times within the while loop, causing it to increment twice.

using the for loop is much cleaner then as incrementing is done within the expression for you

like image 38
RobertPitt Avatar answered Nov 24 '25 21:11

RobertPitt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!