note 126810 added to function.array-sum
| From: | rodrigo at adboosters dot com | Date: | Fri, 28 Jan 2022 12:29:09 +0000 |
| Subject: | note 126810 added to function.array-sum | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-217554@lists.php.net to get a copy of this message | ||
If you want to calculate the sum in multi-dimensional arrays:
<?php
function array_multisum(array $arr): float {
$sum = array_sum($arr);
foreach($arr as $child) {
$sum += is_array($child) ? array_multisum($child) : 0;
}
return $sum;
}
?>
Example:
<?php
$data =
[
'a' => 5,
'b' =>
[
'c' => 7,
'd' => 3
],
'e' => 4,
'f' =>
[
'g' => 6,
'h' =>
[
'i' => 1,
'j' => 2
]
]
];
echo array_multisum($data);
//output: 28
?>
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.135 (proxied: 213.94.44.213)
----
Manual Page -- https://php.net/manual/en/function.array-sum.php
Edit -- https://main.php.net/note/edit/126810
Del: integrated -- https://main.php.net/note/delete/126810/integrated
Del: useless -- https://main.php.net/note/delete/126810/useless
Del: bad code -- https://main.php.net/note/delete/126810/bad+code
Del: spam -- https://main.php.net/note/delete/126810/spam
Del: non-english -- https://main.php.net/note/delete/126810/non-english
Del: in docs -- https://main.php.net/note/delete/126810/in+docs
Del: other reasons-- https://main.php.net/note/delete/126810
Reject -- https://main.php.net/note/reject/126810
Search -- https://main.php.net/manage/user-notes.php