Re: Setting counter in variable name within foreach loop

From: Date: Mon, 24 Nov 2003 07:30:28 +0000
Subject: Re: Setting counter in variable name within foreach loop
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-170769@lists.php.net to get a copy of this message
* Thus wrote Jake McHenry (linux@nittanytravel.com): > Is this possible? I've been messing with this for about an hour now, > searching on google for about half hour. Here is what I want to do: > > foreach ($array as $key => $value) > { > $value = explode("|", $value); > $counter = 0; You're reseting the counter inside the loop so your counter below is always going to be zero. > > if ($value[7] == "Yes") > { > $counter++; > $date_$counter = $value[1]; <-- this is line 33 > $dest_$counter = $value[3]; > $dep_$counter = $value[4]; Its possible to do that with something like ${'date_' . $counter} = $value[1]; But that is ugly, I would use one array to hold all the data $data[$counter]['date'] = $value[1]; $data[$counter]['dest'] = $value[3]; $data[$counter]['dep'] = $value[4]; Then in your loop later in the script: foreach ($data as $array) { echo $array['date'], $array['date'], $array['date']; } imo, that makes the code more readable at what you're trying to do. Curt -- "My PHP key is worn out" PHP List stats since 1997: http://zirzow.dyndns.org/html/mlists/

« previous php.general (#170769) next »