Adamski
Adamski

Reputation: 6019

php increment a value

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.

Upvotes: 2

Views: 3518

Answers (6)

RobertPitt
RobertPitt

Reputation: 57268

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

Upvotes: 5

Femaref
Femaref

Reputation: 61437

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

Upvotes: 5

Haim Evgi
Haim Evgi

Reputation: 125466

use only one time ++ , increment

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

Upvotes: 1

dr3w
dr3w

Reputation: 996

You increment it twice, once setting it as a value, and the second time displaying it in option tag

Upvotes: 0

ajreal
ajreal

Reputation: 47321

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

Upvotes: 4

Tom Vervoort
Tom Vervoort

Reputation: 534

You increment $yearBegin twice, one time in the value part, one time in the display part ...

You need to change it so it only increments once

Upvotes: 0

Related Questions