PHP 8.4.24 Released!

Voting

: seven plus two?
(Example: nine)

The Note You're Voting On

rodrigo at adboosters dot com
4 years ago
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
?>

<< Back to user notes page

To Top