Jump to content

Associating Arrays


wft2

Recommended Posts

I have tried looking this up in the PHP manual, online, and in a book I have but I can't seem to figure out what method to use for the following:

I have a form that when submitted creates an array named "products." This array contains varioius product names. When submitted it contains something like this:
Product_A, Product_B, Product_C

I have another array (associative one that I created) named "Prices." It contains product names as the keys and their prices as the values. It was created like this:
$Prices["Product_A"] = 95;
$Prices["Product_B"] = 174;
$Prices["Product_C"] = 185;
$Prices["Product_D"] = 103;
$Prices["Prodcut_E"] = 220;


I am trying to find a way to automatically calculate a total price for all the products in the "products" array based on the values (prices) found in the "prices" array. The products array will be different each time the form is submitted. I am not sure how to accomplish this. I don't know if I need a command that automatically creates a new array that contains the prices and then do a sum of it, or if there is a better method that involves creating a variable of some kind.

If I could just find a way to create a new array that in this case contains 95, 174, 185 I would be happy. I know how to do a sum on an array.

Can anybody point me in the right direction? I am going about this all wrong?

Thanks!
Link to comment
https://forums.phpfreaks.com/topic/4673-associating-arrays/
Share on other sites

[!--quoteo(post=353872:date=Mar 11 2006, 03:14 AM:name=txmedic03)--][div class=\'quotetop\']QUOTE(txmedic03 @ Mar 11 2006, 03:14 AM) [snapback]353872[/snapback][/div][div class=\'quotemain\'][!--quotec--]
[code]$total = 0;

while (list($key,$val)=each($products)) {
  $total += $prices[$val];
}
echo $total;
[/code]

I think this might be what you are looking for.
[/quote]


That is exactly what I was trying to do. I had tried doing a "foreach" loop and I couldn't make that work. But the "while" loop that you provided worked perfectly.

Thanks for your help. I appreciate it.
Link to comment
https://forums.phpfreaks.com/topic/4673-associating-arrays/#findComment-16554
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.