How to count number of consecutive null values in array

125 views Asked by At

I have an array of customers that has a nested array of payments.

"customer_1" => array:4 [▼
 0 => "211.79"
 1 => "206.20"
 2 => "0.00"
 3 => "0.00"
 4 => "220.90"
]

 "customer_2" => array:4 [▼
 0 => "0.00"
 1 => "0.00"
 2 => "0.00"
 3 => "0.00"
 4 => "220.90"
]

I need to count, for each customer, the amount of consecutive payments, starting from the top of the array that are 0.00.

So I would need it to return something like:

"customer_1" => 0
"customer_2" => 4

I've tried a bunch of while and foreach loops but can't get it to work:

@php($count = 0)

    @foreach($array as $arr)

        @if($arr = "0.00")
            @php($count = $count + 1)
        @else
            @continue
        @endif

    @endforeach
3

There are 3 answers

1
TsaiKoga On BEST ANSWER

Check the first element, if it is 0.00, then just calculate the consecutive 0.00, or just break the loop:

$count = 0;
if ($array[0] == "0.00") {
    foreach($array as $item) {
        if($item == "0.00") {
            $count += 1;
        } else {
            break;
        }
    }
}
return $count;

For blade:

@php($count = 0)

@if($arr[0] == "0.00")
@foreach($array as $arr)

   @if($arr == "0.00")
      @php($count += 1)
   @else
      @break
   @endif

@endforeach
@endif
2
Neeraj Amoli On

you are assigning value to variable inside if condition , you need to compare "0.00" inside if condition .

@php($count = 0)

  @foreach($array as $arr)

    @if($arr == "0.00")
        @php($count = $count + 1)
    @else
        @continue
    @endif

 @endforeach
1
Karan Khimani On
$sum = 0;

foreach($items as $item) {
    $sum += $item;
}

echo $sum;

Try this @dexx