Warm tip: This article is reproduced from stackoverflow.com, please click
arrays php

Get sum of array till number

发布于 2020-03-27 10:26:28

Now I have an array which keeps varying but is like this:-

  Array ( [0] => 10000.00000000 [1] => 10001.00000000 [2] => 1000.00000000 )

I have an amount lets say

 10020.00000000

How do I loop this array such that it stops when it finds that the amount sum is reached and it cannot take more value. Like the array should loop till [1] and record the value as [0] + [1] are only required as subtracting value from [0] leaves us with 0 and [1] leaves with 9981. Thus third value is not required as second is still not 0. Thanks for understanding

Questioner
Zooocc Refback
Viewed
93
DaCurse 2019-07-03 23:20

You can loop through all the elements using foreach and summing then, also checking whenever the sum is equal to the value you want, then using break to exit the loop:

$arr = array(10000.00000000, 10001.00000000, 1000.00000000);
$sum = 0;
foreach($arr as $num)
{
    $sum += $num;
    if($sum >= 10020.00000000) break;

}