Return to Snippet

Revision: 59662
at September 23, 2012 06:29 by eortiz


Updated Code
/**
 * sum values in array
 *
 * @param array $arr
 * @param string [optional]$index
 * @return int result
 */
function array_sum_key( $arr, $index = null ){
    if(!is_array( $arr ) || sizeof( $arr ) < 1){
        return 0;
    }
    $ret = 0;
    foreach( $arr as $id => $data ){
        if( isset( $index )  ){
            $ret += (isset( $data[$index] )) ? $data[$index] : 0;
        }else{
            $ret += $data;
        }
    }
    return $ret;
}

//## To sum elements on a multidimensional finding defined key = 'pv' array

$sum = 0;
$array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($array_obj as $key => $value) {
    if($key == 'pv')
        $sum += $value;
}
echo $sum;

Revision: 59661
at September 23, 2012 06:25 by eortiz


Initial Code
/**
 * sum values in array
 *
 * @param array $arr
 * @param string [optional]$index
 * @return int result
 */
function array_sum_key( $arr, $index = null ){
    if(!is_array( $arr ) || sizeof( $arr ) < 1){
        return 0;
    }
    $ret = 0;
    foreach( $arr as $id => $data ){
        if( isset( $index )  ){
            $ret += (isset( $data[$index] )) ? $data[$index] : 0;
        }else{
            $ret += $data;
        }
    }
    return $ret;
}

Initial URL

                                

Initial Description
Sum all elements of a bidimensional or multi-dimensional array with an assigned key

Initial Title
Sum keyed elements of an array

Initial Tags
math, array

Initial Language
PHP