Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.