# How do I calculate the total of a shopping cart?

I have the following cart implemented by a custom module I wrote. The columns are stored in 2 associative arrays.

``````\$jcartItemQty = \$_POST['jcartItemQty'];
\$jcartItemPrice = \$_POST['jcartItemPrice'];
``````

This is what those array could contain:

```     [jcartItemQty] => Array
(
 => 3
 => 1
)

[jcartItemName] => Array
(
 => Armas Jarnefelt - LAULAJAN KOTI
 => Jean Sibelius - Kullervo
)

[jcartItemPrice] => Array
(
 => 110
 => 120
)
```

I need to combine somehow the arrays into one that looks like `\$combined = (3 => 110, 1 => 120)` in order to be able to calculate the total. `array_merge()` is not working because will only concatenate those 2 arrays.

``````foreach (\$combined as \$key => \$item) {
\$total += \$key * \$item;
}
``````

I need to display the total in a form item like this:

``````foreach (\$jcartItemPrice as \$key => \$value) {
\$form['jcartItemPrice'][\$key] = array(
'#type' => 'textfield',
'#value' => isset(\$value) ? \$value : '',
);
}

\$form['total'][\$key] = array(
'#type' => 'textfield',
'#value' => isset(\$value) ? \$value : '',
);
``````

Is there a way to do this?

Assuming the array keys of each array will always match (and that is what you're using to tie the two arrays together):

``````\$total = 0;
foreach (\$jcartItemPrice as \$key => \$price) {
\$total += \$price * \$jcartItemQty[\$key];
}
``````

You can use array_merge() to merge two arrays into one.

It looks like you're trying to overengineer things. This is a simple solution:

``````\$combined = array();
for (\$i = 0; \$i < count(\$jcartItemQty); \$i++) {
\$combined[] = array(\$jcartItemQty[\$i], \$jcartItemPrice[\$i]);
}
``````
• Thank you Florian, nice way to pair 2 matrices. I will keep in my code snippets. Clive has a nice solution to calculate without pair it so I think we both overengineered it :) - it was my idea to pair up things :)) – drupal_stuff_alter Feb 29 '12 at 9:25