I have an array of values both positive and negative:
$numbers=['10','-2','-1','8','-7','1','-2','-3'];
I need to echo the results as:
numbers[0]=10;
numbers[1]=8;
numbers[2]=7;
numbers[3]=8;
numbers[4]=1;
numbers[5]=1;
numbers[6]=-1;
numbers[7]=-4;
Basically I take the first value that is always positive, echo that value, subtract the first negative value, echo the results, the second, etc until I found the next positive value, I echo that value, subtract from this value that becomes now reference the second negative value and so on…
I tries this in a loop but I can’t manage to "break" the results after finding the second positive number – the numbers keep adding at the result from the first set of positive + negative values – even when using unset….
$i=0;
$sum=0;
while ($i < count($numbers)){
$sum=$sum+$numbers[i];
if($numbers[i]>0)
{
echo $numbers[i];
}
else
{
echo $sum;
}
}
2
Answers
You need to reset
$sum
to the number whenever you get a positive number.