-3

I am trying to multiply two array values with each other with the following formula: Qty* Price = total of each multiple, then sum of all.

Array
(
[qty] => Array
    (
        [0] => .6
        [1] => .2
        [2] => .4
        [3] => .75
        [4] => 0.3
    )

[price] => Array
    (
        [0] => 1.2
        [1] => 0.5
        [2] => 0.8
        [3] => 12
        [4] => 2
    )

)

I could not figure out how to do that. Saw few example regarding the multiply in which they fixed value i.e. 2 or 5 etc. But in my case each qty has different price. Please can somebody suggest how to do that.

5
  • 1
    What do you have so far? Commented Jan 11, 2013 at 2:04
  • From the wording of the question I am not 100% sure what you mean. Do you have an array of prices and an array of quantities. Or is the key the quantity and the value the price? Also please post some code explaining how you get your variables. Commented Jan 11, 2013 at 2:05
  • are the arrays of equal lengths? Commented Jan 11, 2013 at 2:54
  • I'd like this question to be reopened. I edited it to make it more clear, with an example of the expected result and some boundaries that allow for a specific answer. I found myself with the very same problem and looking for an elegant way to solve it, and since there have been already more than 2,000 views, I think it would be worth a reopening. What do you think @jeroen? Commented Mar 7, 2017 at 18:25
  • @clami219 This question was closed as it does not show any effort and apart from that it was answered as far as the OP is concerned. If you have another question, you should ask a new one, not make big changes to this question. Commented Mar 7, 2017 at 18:34

1 Answer 1

4

The following will work as long as both arrays are the same size.

for($i = 0; $i < count($qty); $i++) {
    $result[] = $qty[$i] * $price[$i];
}

The result will be in the $result array.

To get the sum:

echo "sum(result) = " . array_sum($result) . "\n";
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks njk for your reply, this is very helpful!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.