Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto increment years in loop every year [duplicate]

Tags:

php

Possible Duplicate:
How to increment date with 1 (day/year) in PHP?

Im not really sure where to begin with this but im trying to make a year start at 1928 and stop at 1948 and for every year the years increment by one so since its 2012 the date ranges are 1928 - 1948 and for 2013 it would be 1929 - 1949 and 2014 would be 1930 - 1950 and so on...

right now i just have a basic loop for when to start and stop the years but its not too dynamic, like i said im pretty much at a blank on where to begin other then date('Y')+1.

for($i=1928;$i<=date('Y');$i++)
{
    echo '<option value='.$i.'>'.$i.'</option>';
    if($i == '1948'){break;}
}
like image 623
Suzed Avatar asked Oct 01 '12 20:10

Suzed


3 Answers

So you want it to go between current year minus 84 and the current year minus 64? Use this code:

$firstYear = (int)date('Y') - 84;
$lastYear = $firstYear + 20;
for($i=$firstYear;$i<=$lastYear;$i++)
{
    echo '<option value='.$i.'>'.$i.'</option>';
}

Edit: updated for performance. Current year is determined before the loop (per Pitchinnate's comment).

like image 53
Adam Plocher Avatar answered Oct 21 '22 10:10

Adam Plocher


Try this:

$year = date('Y');
$add = $year - 2012;
$min = 1928 + $add;
$max = $min + 20;
for($i=$min;$i<=$max;$i++)
{
    echo '<option value='.$i.'>'.$i.'</option>';
}

I isn't a good idea to have date('Y') or any evaluations done on the for loop as it gets calculated every time through the loop. Article about this.

like image 3
Pitchinnate Avatar answered Oct 21 '22 12:10

Pitchinnate


Something like this?

$base_year = 2012;
$start_year = $base_year - 84;
$end_year = $start_year + 20;

for( $i = $start_year; $i <= $end_year; $i++)
{   
    echo '<option value='.$i.'>'.$i.'</option>';
}
like image 2
John Avatar answered Oct 21 '22 12:10

John