View Full Version : Incrementing a variable's name

11-22-2007, 04:01 AM
I've created a table with six quantity/price pairs of values (among other items). Is there a better way to display these pairs other than creating a line for each pair?

So instead of ...

echo $row->qty1 . " " . $row->price1;
echo $row->qty2 . " " . $row->price2;

That I could loop through the variable names?

for $x = 1 to 6
$vname1 = "qty" . $x;
$vname2 = "price" . $x;
echo $row->(vname1) . " " . $row->($vname2);


11-22-2007, 05:47 AM
1st Normal Form is broken here. Any time you see column names ending in "1", "2", etc, you know you need to break that data into a new table and use a foreign key to relate it to the main table.

11-22-2007, 06:27 PM
I knew I would get taken to task over that one. I know that I should but in this case I am taking a poor form short cut intentionally.

But... is my original question possible in PHP?

11-22-2007, 06:45 PM
It's possible, using variable variables. But you're looping over them already, so I don't see why you would need/want to.

11-23-2007, 08:48 AM
personally I tent to to use while loops rather than for each as loops for some reason seated in other languages.

$foo = 0;
while( $foo < 6){
//echo[$foo] etc....

11-23-2007, 03:54 PM
You nearly had the code right there :)

for($x = 1; $x <= 6; $x++) {
$vname1 = 'qty'.$x;
$vname2 = 'price'.$x;
echo $row->$vname1.' '.$row->$vname2;

I would've thought you've gotten $row from a db call though?

foreach(mysql_fetch_object($result_id) as $row) {
echo $row->qty.' '.$row->price;

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum