Reputation:
$amount = 2;
$array = array(3,6,12);
foreach($array as $a){
$total = $a*$amount;
}
result for only the last element:
int(24) int(12)
result must be: int(6) int(12) int(24)
I want to calculate a sum of all the elements in the array, but only the last element is calculated.
Upvotes: 0
Views: 233
Reputation: 445
use array_map:
function double($v)
{
return $v * 2;
}
$a=array(3, 6, 12);
$resArr = array_map("double" ,$a));
the result will be an array [6, 12, 24]
Upvotes: 0
Reputation: 347
If you say that you want calculate sum elements of array $amount isn't neccesary.
You can use array_reduce
You can see documentation here
function sumArray($carry, $item)
{
$carry += $item;
return $carry;
}
array_reduce($array, "sumArray");
if you need get array with (6,12,24) you can use
function sumArray($item)
{
return $item*2;
}
array_map("sumArray",$array); //array(6,12,24)
Upvotes: 1
Reputation: 370
Iterate over each element of the array passed as reference and update inside the loop, like this:
$amount = 2;
$array = array(3,6,12);
foreach($array as &$a){
$a = $a*$amount;
}
var_dump($array);
Upvotes: 2
Reputation: 878
If this is indeed your code you should get a lot of undefined errors. You say that you want to get the sum, so why are you multiplying with $amount
?
You want to do this:
<?php
$array = array(3,6,12);
$total = 0;
foreach($array as $a){
$total += $a;
}
Or even easier: Just use array_sum:
array_sum — Calculate the sum of values in an array
Like so:
<?php
$array = array(3,6,12);
echo array_sum($array);
Upvotes: 0