RE: [PHP] using a counter in a foreach loop

From: Date: Tue, 26 Mar 2002 14:56:11 +0000
Subject: RE: [PHP] using a counter in a foreach loop
Groups: php.general 
Request: Send a blank email to php-general+get-90193@lists.php.net to get a copy of this message
Hi Erik, > I have a foreach loop, where I execute some > commands for each element in a certain array. > One thing I would like to add to this loop is a > counter, so that on each iteration of the loop > I have a next higher number. The following does > not work: > > foreach ($months) { > $i = 1; > // do some things > $i++; > } > > because in each new iteration of the loop, $i > is reset to 1. Is there a way that I can > achieve this effect? Thanks for any advice, Put the $i = 1 outside the loop. $i = 1; foreach ($months) { // do some things $i++; } Incidentally, I *really* hope you're not planning on doing: $i = 1; foreach ($months) { echo "month ". $i. " is ". $months[$i]. "<br>"; $i++; } if you are, I suggest you play around with foreach ($months as $currentMonth) { and see where it gets you :-) Cheers Jon

« previous php.general (#90193) next »