If I have a multidimensional associative array is it possible to use recursion to sum all the values? I can't figure out how to do this? Any ideas?

e.g.

$myArray = array (0=>19,
1=>32,
2=>array(0=>12,
1=>15
)
3=>9,
4=>array(0=>2,
1=>5
)
)

    This is the shortest function
    I could come up with.

    function will test if element is_array
    and add result of a recursive call if it is
    otherwise it will just add value, $val

    <?php
    
    function sum_array($arr){
    	$res = 0;
    	foreach($arr AS $val)
    		$res += is_array($val)? sum_array($val) : $val;
    	return $res;
    }
    
    $myArray = array (0=>19,
    1=>32,
    2=>array(0=>12,1=>15),
    3=>9,
    4=>array(0=>2,1=>5)
    );
    
    echo sum_array($myArray); // will display 94
    
    ?>

      I didn't realize there was such a function 'is_array'. I was trying all sorts of weird stuff to mimic that. Thanks.

        I prefer letting php to the work for me

        function addVal($v = 0, $k = 0) {
        	static $sum = 0;
        	if (is_int($v))
        		$sum += $v;
        	return $sum;
        }
        array_walk_recursive($myArray, 'addVal');
        echo addVal();
          Write a Reply...