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
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;
}
How do I echo the number of values out?
For each iteration? just echo
$num
which is the current number in each iterationIt's best to compare with an inequality. With floats, there's a good chance
$sum
will never exactly equal the target value, so the loop will continue past it.@DaCurse I want to echo out the number of objects in the array that were there before the break
@DaCurse like it should be 2 in this case