samedi 27 juin 2015

Adding up values in array

I am trying to count elements in an array separated by one or more zeroes (0) Example: [3,2,1,0,5,4,0,0,8,4]. 3+2+1 , 5+4 , 8+4 Output: [6,9,12] I have written the following function:

function countElementsInArray(){
$array = [1,2,4,0,9,8,4,0,7,1,2,6];

$countArr = [];
$count = 0;
$test = 0;

for($i = 0; $i < count($array); $i++){
    if( $array[$i] != 0 ) {
       $count += $array[$i];
    } 
    //else if($array[$i] == 0 || $array[$i - 1] == 0){
    else{
        $count = 0;
        $test += 1;
    }
    $countArr[$test] = $count;
}
return $countArr;

}

This works fine if I have only one "0" in the array. I can't figure out how to add up the values if I have 2 zeroes. Any idea how to solve this problem?

Aucun commentaire:

Enregistrer un commentaire