problem with for() and foreach()

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JKM
Forum Contributor
Posts: 221
Joined: Tue Jun 17, 2008 8:12 pm

problem with for() and foreach()

Post 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?
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

Re: problem with for() and foreach()

Post 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    
}

JKM
Forum Contributor
Posts: 221
Joined: Tue Jun 17, 2008 8:12 pm

Re: problem with for() and foreach()

Post by JKM »

Haha, I solved it. I wrote $i inside the foreach loop - and not $y. :oops:

Thanks for trying!
Post Reply