note 57232 deleted from function.array-sum by levim
| From: | levim@php.net | Date: | Tue, 18 Mar 2014 19:44:10 +0000 |
| Subject: | note 57232 deleted from function.array-sum by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-198971@lists.php.net to get a copy of this message | ||
Note Submitter: mroach at mroach dot com
----
I ran into a situation where I only wanted to sum elements of an array for certain keys. For that, I
wrote this function
<?
function array_sum_by_key()
{
$args = func_get_args();
$arr = array_shift($args);
$to_sum = is_array($args[0]) ? $args[0] : $args;
$sum = 0;
foreach ( $arr as $k=>$v ) {
if ( in_array($k, $to_sum) ) {
$sum += $v;
}
}
return $sum;
}
$arr = array (
'dog' => 1,
'cat' => 2,
'rat' => 4,
'mat' => 8,
'bat' => 16
);
echo array_sum_by_key($arr, 'dog', 'mat');
// Result: 9
?>
Alternatively, you can pass the keys to sum as an array
<?
$to_sum = array('dog', 'bat');
echo array_sum_by_key($arr, $to_sum);
// Result: 17
?>