Sagar Singh Sagar Singh - 18 days ago 5
PHP Question

How to calculate two arrays value

I have two arrays One with quantity and one array with price i want to multiply both of the array and finds its sum

Here are the two arrays

Quantity Array

Array
(
[0] => 100
[1] => 200
[2] => 300
[3] => 600
)


Price Array

Array
(
[0] => 100
[1] => 200
[2] => 150
[3] => 300
)


I want to get another array which will give me total if above two array like this

Array
(
[0] => 10000
[1] => 40000
[2] => 45000
[3] => 180000
)


Above is the multiple of above two arrays

Till now here is what I've tried

$quantity = $_POST['quantity'];
$price = $_POST['price'];
$total_price = array();
foreach ($price as $key=>$price) {
$total_price[] = $price * $quantity[$key];
}


But above method gives me error

Answer
$quantity = $_POST['quantity']; 
$price = $_POST['price']; 
$total_price = array();

// assumption: $quantity and $price has same number of elements
// get total elements' count in variable. don't call count function everytime in loop.
$len = count($quantity);
for ($i=0; $i<$len; $i++) {
    $total_price[] = $price[$i] * $quantity[$i];
}

// var_dump($total_price) will give you desired output.
Comments