Forum Moderators: coopster
If I understand the question right that'll do it.
If you want to increment another var to tack on then this would do it also.
$new_id = 0;
foreach($_POST['hid_price'.$id] as $price)
{
$new_id ++;
$total.$new_id = ($price*$qty);
}
JAG
BTW, it's easy to be baffled, I was too. This is a most unusual concept, that of variable variables, but also a very useful and powerful one in the right circumstances.
The code:
$total = 'total' . $id;
$$total = ($price*$qty);
Does the following:
It creates a new variable called $total and gives it a value which is the text "total" plus the VALUE of the variable $id appended to it.
For instance, if the variable $id = 4, then the code:
echo $total;
would result in the text "total4" being displayed to the browser.
So, the VALUE of the variable $total, is the text "total4".
Remember that :-)
Next it creates another variable, $$total.
This is in effect saying "create me a new variable whose NAME is:
$ plus the VALUE of the variable, $total.
Here's the key:
Internal to PHP (and your brain) this new variable's NAME, $$total, is really INTERPRETED as $total4.
The first $ instantiates the new variable. The "$total" part is a reference to the VALUE of $total. Thus, since "total4" is the value of $total, then $$total is in effect a new variable named $total4.
WHO CARES!?!
On rare occasions, one needs to build a temporary "database" in the session rather than the mySQL database. Think shopping cart or building an invoice before saving it to the database.
When you add an item to a shopping cart or invoice or what have you, and give it a qty other than "1", then you have to have a variable to hold a subtotal of price*qty for the item. That subtotal variable needs a unique name that ties it to the item for which it is holding the subtotal. So tacking the item ID onto the variable NAME is a dependable solution.
The above code facilitates tacking an item id onto the NAME of a new variable.
I hope this helps!
darn me always wanting to spend time with my family ;)
at least I can add that 1 line owuld be easier
$total = 'total' . $id;
$$total = ($price*$qty);
into
${'total' . $id} = ($price*$qty);
I like using this format when doing repetetive tasks, use a couple counters, if you get complex a ouple of control arrays so I know what the variables end up being named, who knows what can happen, and we're off to the races.
I have made some interesting things, small amount of code, massive amount of work.
sometime I could show you what it's really good for where no variable names are ever declared, a couple control files included and the script never has any varnames, all variable, tons of fun.