Page 1 of 1

problem with for() and foreach()

Posted: Tue May 11, 2010 8:45 pm
by JKM
For some reason, this doesn't work out the way I want it to:

Code: Select all

for($i = 2005; $i <= date('Y'); $i++) {
    $year[$i]    = $i;
}
print_r($year);
foreach($year as $y) {
    echo $i.', ';
}

/* -----------------------------> returns:

    Array
    (
        [2005] => 2005
        [2006] => 2006
        [2007] => 2007
        [2008] => 2008
        [2009] => 2009
        [2010] => 2010
    )
    2011, 2011, 2011, 2011, 2011, 2011, 
*/
... when this works:

Code: Select all

$year[2005] = 2005;
$year[2006] = 2006;
$year[2007] = 2007;
$year[2008] = 2005;
$year[2009] = 2009;
$year[2010] = 2010;

foreach($year as $y) {
	echo $y.', ';
}
So how can I make it work when it's generated by the for() loop?

Re: problem with for() and foreach()

Posted: Tue May 11, 2010 9:23 pm
by yacahuma
dont use date in a loop, dont remember why. You have a key=>value array, Use it as such.

Code: Select all

$dt = date('Y');
for($i = 2005; $i <=$dt ; $i++) {
    $year[$i]    = $i;
}
foreach($year as $k=>$v) {
    //do whatever    
}


Re: problem with for() and foreach()

Posted: Tue May 11, 2010 10:05 pm
by JKM
Haha, I solved it. I wrote $i inside the foreach loop - and not $y. :oops:

Thanks for trying!