Sum values of multidimensional array by key without loop
In php 5.5+ you can just used array_column
and array_sum
like so:
$value = array_sum(array_column($arr,'f_count'));
You need to couple it with array_map()
to select the f_count
column first:
array_sum(array_map(function($item) { return $item['f_count']; }, $arr));
Of course, internally, this performs a double loop; it's just that you don't see it inside the code. You could use array_reduce()
to get rid of one loop:
array_reduce($arr, function(&$res, $item) { return $res + $item['f_count'];}, 0);
However, if speed is the only interest, foreach
remains the fastest:
$sum = 0;foreach ($arr as $item) { $sum += $item['f_count'];}
This is thanks to the "locality" of the variables that you're using, i.e. there are no function calls used to calculate the final sum.
for these type of situation foreach loop is the best possible option but if u have to do this for multiple times on a single page then u should put foreach loop in a function so that your code remain clean
function sum_index($arr, $col_name){ $sum = 0; foreach ($arr as $item) { $sum += $item[$col_name]; } return $sum;}
Edit
After searching alot I found that array_column
function exist in php 5.5 + to get all values of single column as an array.
For users having lower version You can use following function and call it with array sum if you want sum of all values as well.
//to get all values of single column from multidimensional array, this function exist in php 5.5 or greater.if(!function_exists("array_column")){ function array_column($array,$column_name) { return array_map(function($element) use($column_name){return $element[$column_name];}, $array); }}
If you want to get all values of single column then call above function like this:
$newArray = array_column($array,$column_name);
If you want sum of all values of single column then use following code:
$newArraySum = array_sum(array_column($array,$column_name));