Reputation: 69
I have a challenge multiplying two arrays. this is what i intend doing
Array1 ( [0] => 2 [1] => 2 )
Array2 ( [0] => 8000.00 [1] => 1234.00 )
Every time i multiply this it breaks it down into 4 and returns a result as this
Array ( [0] => 16000 [1] => 16000 [2] => 2468 [3] => 2468 )
However when i pass single a single data it gets it right. Here is my code, i'll appreciate any help i can get. Thanks
$total = array();
foreach($office_price as $price){
foreach($office_quantity as $quantity){
$total[] = $price * $quantity;
}
}
Upvotes: 1
Views: 21946
Reputation: 11
$total_in_array = array_map(function($x, $y) { return $x * $y; }, $office_price, $office_quantity); // This will return array of multiplied numbers
$total = array_sum($total_in_array); // This will return the total
Upvotes: 1
Reputation: 1373
function a($a, $b)
{
$r = [];
for($i = 0; $i < (count($a)); $i ++)
{
$r[] = $a[$i] * $b[$i];
}
return $r;
}
Upvotes: 0
Reputation: 315
Use Array map function it will works
$total_hours = array(10, 20, 30);
$hourly_rate = array(15, 10, 15);
$total_pay = array_map(function($hour, $rate) {
return $hour * $rate;
}, $total_hours, $hourly_rate);
Upvotes: 1
Reputation: 6124
$a= array (2,2);
$b= array(8000,1234);
$total = array();
for ($i=0;$i<count($a);$i++) {
$total[] = $a[$i] * $b[$i];
}
Upvotes: 1
Reputation: 780889
You can give multiple arrays to array_map
, and it will process the corresponding elements:
$total = array_map(function($x, $y) { return $x * $y; },
$office_price, $office_quantity);
Upvotes: 19
Reputation: 17651
To multiply two arrays, you must do it elementwise: no nested loops involved. For example, if you want to get $total[2]
, then its value is $office_price[2] * $office_quantity[2]
. Thus the one foreach loop. To loop through keys, use ... as $key => $price
.
$office_price = array(10, 100, 1000);
$office_quantity = array(1, 2, 3);
$total = array();
foreach($office_price as $key => $price){
$total[$key] = $price * $office_quantity[$key];
}
var_dump($total);
// array(3) { [0]=> int(10) [1]=> int(200) [2]=> int(3000) }
Upvotes: 0
Reputation: 2856
You loop through both arrays, so you get every value twice.
As you know, an array is built up using keys and values.
Use your foreach to that extent:
$total = array();
foreach ($office_price as $key=>$price) {
$total[] = $price * $office_quantity[$key];
}
You only need to loop one array, and by using the value from the second array with the same key, you get the proper result.
Upvotes: 3
Reputation: 1761
Use this
$total = array();
for($i=0;$i<count($office_price);$i++){
$total[] = $office_price[$i] * $office_quantity[$i];
}
Upvotes: 0