Monday, 2 February 2015

Array Sum Recursive

Array Sum Recursive

This handy function will take an array, or multi-dimensional array of numbers and return the sum of all values.

<?php
    
function arraySumRecursive($array)
    {
        
$total 0;
        foreach(new 
recursiveIteratorIterator( new recursiveArrayIterator($array)) as $num)
        {
            
$total += $num;
        }
        return 
$total;
    }
?>

EXAMPLE CODE


<?php

    
/*** a flat array ***/
    
$array = array(1020534129);

    
/*** add the values ***/
    
echo arraySumRecursive($array)."<br />";


    
/*** a multi dimensional array ***/
    
$array = array(10205,  
        array(
523,  
            array(
53,  
                array(
210
                    array(
191
                ),

            
), 2
        
), 
    
);

    
/*** add the values ***/
    
echo arraySumRecursive($array);?>

DEMONSTRATION

198
100

0 comments:

Post a Comment