开发者

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,2开发者_开发问答001,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.


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


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


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


use only one time ++ , increment

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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜