Re: build variable names from variables

From: Date: Mon, 14 Apr 2003 15:21:39 +0000
Subject: Re: build variable names from variables
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-143786@lists.php.net to get a copy of this message
> I have a script with snippets of code looking like this: > > if ($row->category == RMA) {$num_RMA++;} > if ($row->category == firmware) {$num_firmware++;} > if ($row->category == other) {$num_other++;} > .. > echo "Category RMA: $num_RMA"; > echo "Category firmware: $num_firmware"; > echo "Category other: $num_other"; > ... > > and so on for about twenty lines each of if and echo lines. > This drives me nuts since Im sure there must be a better way of doing > this. > I have played with the idea of making a variable from the variables. > something like '$num_$row->category++' but php pukes on me everytime I > try. Could someone show me how to set this up using arrays or any > other way that is more efficient and beatiful then using brute if() power? Use an array: $num[$row->category]++; ... foreach($num as $category=>$value) { echo "Category $category: $value"; } The foreach() part would come after you've looped through all of your rows. Maybe throw in some checking that sees if $num[$row->category] is set before incrementing it and you should be golden. ---John Holmes...

« previous php.general (#143786) next »