I am trying to count elements in an array separated by one or more zeroes (0).
Example:
[1,2,4,0,9,8,4,0,0,7,1,2,6]
1+2+4, 9+8+4, 7+1+1+2+6
Output: [7,21,16]
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 two zeroes. Any idea how to solve this problem?
EDIT: the problem is when I have array like this: [1,2,4,0,9,8,4,0,0,7,1,2,6] with two "0" next to each other: print_r(countElementsInArray())
Array ( [0] => 7 [1] => 21 [2] => 0 [3] => 16 )
and what I am trying to reach is this:
Array ( [0] => 7 [1] => 21 [2] => 16 )
Array ( [0] => 7 [1] => 21 [2] => 16 )with this array:[3,2,1,0,5,4,0,0,8,4]?!