note 108555 added to function.array-sum
| From: | pablo114 at interia dot eu | Date: | Sun, 06 May 2012 18:17:48 +0000 |
| Subject: | note 108555 added to function.array-sum | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-187493@lists.php.net to get a copy of this message | ||
If you want to sum all values (horizontal or vertical) use this function:
<?php
function sumArray($array, $params = array('direction' => 'x', 'key'
=> 'xxx'), $exclusions = array()) {
if(!empty($array)) {
$sum = 0;
if($params['direction'] == 'x') {
$keys = array_keys($array);
for($x = 0; $x < count($keys); $x++) {
if(!in_array($keys[$x], $exclusions))
$sum += $array[$keys[$x]];
}
return $sum;
} elseif($params['direction'] == 'y') {
$keys = array_keys($array);
if(array_key_exists($params['key'], $array[$keys[0]])) {
for($x = 0; $x < count($keys); $x++) {
if(!in_array($keys[$x], $exclusions))
$sum += $array[$keys[$x]][$params['key']];
}
return $sum;
} else return false;
} else return false;
} else return false;
}
?>
Some examples now:
<?php
$array1 = array('myKey1' => 2, 'myKey2' => 5, 'myKey3' => 8);
$array2 = array(array('myKey1' => 2, 'myKey2' => 5, 'myKey3'
=> 8), array('myKey1' => 2, 'myKey2' => 5, 'myKey3' =>
8));
/*Sum an array*/
print_r(sumArray($array1)); //outputs: 15
/*Sum an array without adding "myKey2" key*/
print_r(sumArray($array1, array('direction' => 'x'),
array('myKey2'))); //outputs: 10
/*Sum a multi-dimensional array horizontally without adding "myKey3" key*/
print_r(sumArray($array2[0], array('direction' => 'x'),
array('myKey3'))); //outputs: 7
/*Sum a multi-dimensional array vertically (by "myKey1" key) without adding [0] row*/
print_r(sumArray($array2, array('direction' => 'y', 'key' =>
'myKey1'), array('0'))); //outputs: 2
?>
----
Server IP: 69.147.83.197
Probable Submitter: 81.219.136.130
----
Manual Page -- http://www.php.net/manual/en/function.array-sum.php
Edit -- https://master.php.net/note/edit/108555
Del: integrated -- https://master.php.net/note/delete/108555/integrated
Del: useless -- https://master.php.net/note/delete/108555/useless
Del: bad code -- https://master.php.net/note/delete/108555/bad+code
Del: spam -- https://master.php.net/note/delete/108555/spam
Del: non-english -- https://master.php.net/note/delete/108555/non-english
Del: in docs -- https://master.php.net/note/delete/108555/in+docs
Del: other reasons-- https://master.php.net/note/delete/108555
Reject -- https://master.php.net/note/reject/108555
Search -- https://master.php.net/manage/user-notes.php