Dynamic Variable

Hello

I have a table with a lots of fields. Some fields are like this :

cost1
cost2
cost3

I query the database and get the results as an object via mysql_fetch_object.

but for some reason, I want something like this :

$cost = $row->cost."1"; 

actually I want to put it in the loop and the loop have some calculations based on the value of the cost. So I want to put the loop counter variable with the $row->cost thing, so that, it can be interpreted like this :

CODE :
$cost = $row->cost.“1”;

INTERPRETATION:
$cost = $row->cost1;

Please guide me how this can be achieved.

Thanks
Zee

Because that’s interpreting it as two separate items it’s not going to work ($a->b) . (“1”). Try using a variable to hold both parts first.

$field = "cost" . "1";
$cost = $row->$field;

You can also


$n=1;
echo $o->{"a$n"};

Off Topic:

This might be a good time to redesign your database so that you have a separate table for this repeating column.

Thanks a lot ! You people ROCKs !

So we have two approaches:
1>

$n=1;
echo $o->{"a$n"}; 

2>

$n=1;
$var = "a".$n;
echo $o->$var
//or 
echo $o->{$var}

Hi

I tried following code :

$m7 = "M7 = 1<br>";
$m8 = "M8 = 1<br>";
$m9 = "M9 = 1<br>";
$m10 = "M10 = 1<br>";
$m11 = "M11 = 1<br>";
$m12 = "M12 = 1<br>";
$m13 = "M13 = 1<br>";
$m14 = "M14 = 1<br>";

for($a=7; $a<=14; $a++){
   $var = "m".$a; 
   echo ($var) ;
}

But it is not working !

this worked :

for($a=7; $a<=14; $a++)
{
$var = “m$a”;
echo $$var ;
}

echo ($$var);

You’re probably going about things the wrong way if you have to do all this though.

Edit, should have refreshed :S