Array Sum Recursive
This handy function will take an array, or multi-dimensional array of numbers and return the sum of all values.
EXAMPLE CODE
DEMONSTRATION
198100
<?php
function arraySumRecursive($array)
{
$total = 0;
foreach(new recursiveIteratorIterator( new recursiveArrayIterator($array)) as $num)
{
$total += $num;
}
return $total;
}?>
<?php
/*** a flat array ***/
$array = array(10, 20, 5, 34, 129);
/*** add the values ***/
echo arraySumRecursive($array)."<br />";
/*** a multi dimensional array ***/
$array = array(10, 20, 5,
array(5, 2, 3,
array(5, 3,
array(2, 10,
array(19, 1)
),3
), 2, 7
), 3
);
/*** add the values ***/
echo arraySumRecursive($array);?>
Hello Friends! I am Ramana a part time blogger from Hyderabad.
0 comments:
Post a Comment