Can use Array_sum or loop and make sum? - php

Have an array
array(array('a'=>'s','add'=>1),
array('a'=>'s1','add'=>2),
array('a'=>'s2','add'=>3)
...
...
);
I want to sum of all key add together.so result should be 6
Anyone know how to do this?

$sum = 0;
foreach($yourArray as $element) {
$sum += $element['add'];
}
echo $sum;

$sum = 0;
foreach($array1 as $array) {
$sum += $array['add'];
}
echo $sum; // will echo '6'

Unfortunately, array_sum only works on single-dimensional arrays. Since you're working with an array of associative arrays, you're going to have to approach it differently. If you know your array will have the same form as the one you've linked above, you can simply use something like this:
$total = 0;
foreach( $arrs as $arr )
{
$total += $arr['add'];
}
echo $total;
Where $arrs is the array you've defined above.

One liner echo array_sum(array_column($a, "add"));

Related

PHP array_sum - why array_sum is not working for the following script?

I have seen read other posts that are almost similar to my problem.
but I can't find the right answer to my problem.
here I have a $data[4] array that is like the following.
Array ( [0] => 0.84 ) Array ( [0] => 2.79 )
and this my php code for calculating the value in variable $data[4]
$a= array();
foreach(array($data[4]) as $datas) {
$a[] = $datas;
}
print_r($a);
$sum = array_sum($a);
echo $sum;
}
but the results are not calculating, instead of displaying values ​​from the data array $data[4]
like this
0.84
2.79
You got two arrays with 0 index in $data[4]. You have to flatten this $a, you can add extra foreach.
$a= array();
foreach(array($data[4]) as $datas) {
foreach($datas as $item) { // here - extra foreach
$a[] = $item;
}
}
print_r($a);
$sum = array_sum($a);
echo $sum;
}
By the way - consider using var_export to show more precisely what's in your data :)
Assume that your array is like $data[4] = [[0.89],[2.79]] then you can use this code to get sum.
$sum = 0;
foreach($data[4] as $datas) {
$sum += array_sum($datas);
}
echo $sum;

Foreach only repeats last element of array

$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.
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);
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)
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);
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]

Multiply two arrays

I have two arrays which I want to multiply and get the final sum. First one is fixed but the second one could have missing elements. For example:
$array1 = array(1, 2, 3, 4, 5);
$array2 = array(1, 3, 5);
Lets say I've got missing elements $array2[1] and $array2[3]. I want to be able to multiply and sum up the rest as:
$sum = array_sum($array1[0] * $array2[0] + $array1[1] * $array2[1] + $array1[2] * $array2[2] + $array1[3] * $array2[3] + $array1[4] + $array2[5]);
Length of arrays may also vary so can't do it the way I've written it above. Any suggestions?
You can complete the array2 missing values as 1, then make the two array have the same length.
$missingKeys = [1,3];
foreach($missingKeys as $k)
{
$array2[$k] = 1;
}
$sum = 0;
foreach($array1 as $k => $v)
{
$sum += $v * $array1[$k];
}
Ok, I didn't use my own advise, but I think this might work?
$total = 0;
foreach ($array1 as $index => $value)
{
if (isset($array2[$index])) $total += $value*$array2[$index];
else $total += $value;
}
echo $total;
The assumption is that all elements of $array2 are present in $array1, but not necessarily the other way around.
As you wrote in your question that the first array is leading (has all the indexes) you only need to iterate over it and eventually multiply with the value from the second array or one:
$sum = 0;
foreach ($array1 as $k => $v) {
$sum += $v * ($array2[$k] ?? 1);
}
Different to the accepted answer, there is no need to manipulate the second array.
If I understood your question properly, and your looking for array multiplication, you could use 2 for loops, iterating one of them and multiplying. Your probably looking for something like this:
for ($i = 0; $i < count($array1); $i++) {
for ($j = 0; $j < count($array2); $j++) {
$sum += $array1[$i] * $array2[$j];
}
}

get total of multidimensional array

So i have an array which is created like this via a loop
foreach ($items as $item)
{
$item_arr[$id]['count'] = $item->rowcount;
}
Now what i want to do is get the sum of the counts. I know i can just use $sum += $item->rowcount; but i was wondering if there was a more efficient way using something like this outside the loop when the foreach is done:
$sum = array_sum($item_arr[]['count']);
But that doesn't work says it doesn't like [], is there a way to do it or is the best way just to keep count in the foreach loop. Just would like to keep the code cleaner and more readable but maybe its a stupid question?
Where did $id come from?
the best would be $sum += $item->rowcount;
$sum = 0;
foreach ($items as $item) {
$sum += $item->rowcount;
}
echo $sum;
You can use array_reduce() like this
function sum($carry, $item){
return $carry + $item['count'];
}
array_reduce($item_arr, "sum");
A variation of a theme perhaps but like array_reduce you could alternatively use array_walk
$total=0;
$arr=array(
array('count'=>23),
array('count'=>54),
array('count'=>91),
array('count'=>86)
);
array_walk( $arr, function( &$i, $k, &$t ){
$t += $i['count'];
}, &$total );
echo 'total:'.$total;

Counting elements in multidimensional array?

I'm trying to count the nested elements in a multidimensional array. At first I thought I could use COUNT_RECURSIVE, but that counts everything. So I've tried two different approaches, none of them appeal to me. Is there a better way to do it?
$count = 0;
foreach ($topics as $t) {
foreach ($t as $c) {
$count++;
}
}
echo $count;
// or
echo (count($topics, COUNT_RECURSIVE)-count($topics));
function countNested($arr) {
return (count($arr, COUNT_RECURSIVE) - count($arr));
}
I would write this code:
$count = 0;
foreach ($topics as $t) {
$count+= count($t);
}
echo $count;
//The following example will count either one-dimensional or two-dimensional arrays
$values_count = (count($values, COUNT_RECURSIVE) - count($values)?:count($values));

Categories