...

View Full Version : Can you include variables in variable titles? [SOLVED]



Crazydog
06-30-2007, 02:23 AM
I have a foreach loop, and it needs to output different variables for each array value.

i.e.

array has the keys one, two, three

I need the foreach to output variables like:

$onefinal $twofinal $threefinal.

How would I include the key in the variable name?



EDIT: Solved my problem!
I changed the variable I needed to be unique to
${$value}
that way, each of the values of the array would be its own unique variable

here's a snippit:


$sums[one] = "Q1";
$sums[two] = "Q2";
//etc..
foreach($sums as $key => $value){
$sumq = "SELECT SUM($value) FROM results";
$sumr = mysql_query($sumq);
$arr = mysql_fetch_row($sumr);
$finalvalue = $arr[0];
$avg = $finalvalue / $num;
${$value} = round($avg, 2);
}

that gave me unique variables named $Q1, $Q2, etc.

whizard
06-30-2007, 02:35 AM
$num = count($array);
for($i = 0;$i < $num;$i++)
{
$string = key($item);
$$string = $item;
next($array);
}

Hopefully that works for you tho I didn't test it...

It works based on the principle of Variable variables (http://us2.php.net/language.variables.variable).

HTH
Dan



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum