Home > database >  how to create a loop function to sum array data based on increasing index in php
how to create a loop function to sum array data based on increasing index in php

Time:05-25

Excuse me, I want to ask about the iteration step.

i have $data like this

array:6 [▼
      0 => 0
      1 => 0.25
      2 => 0.75
      3 => 0.5
      4 => 0.5
      5 => 0.75
]

but i want to make iteration or loop $result like below

$result[0]=2.75
$result[1]=2.75
$result[2]=2.5
$result[3]=1.75
$result[4]=1.25
$result[5]=0.75

result explanation

$result[0]= 0   0.25   0.75   0.5   0.5   0.75 = 2.75
$result[1]= 0.25   0.75   0.5   0.5   0.75 = 2.75
$result[2]= 0.75   0.5   0.5   0.75 = 2.5
$result[3]= 0.5   0.5   0.75 = 1.75
$result[4]= 0.5   0.75 = 1.25
$result[5]= 0.75 = 0.75

I've tried several times to make this loop function, but it doesn't work, here's my latest code

    for ($i = 0; $i < count($data); $i  ) {
              if (isset($data[$i   1])) {
                     $result  = $data[$i   1];
             } else {
                 $result  = 0;
          }
    }

What is the correct looping function to get the expected result, please help, thanks

  •  Tags:  
  • php
  • Related