Home > OS >  php array negative and positive numbers
php array negative and positive numbers

Time:01-05

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;
    }       
}

CodePudding user response:

You need to reset $sum to the number whenever you get a positive number.

foreach ($numbers as $i => $num) {
    if ($num > 0) {
        $sum = $num;
    } else {
        $sum  = $num;
    }
    echo "numbers[$i] = $sum<br>";
}

CodePudding user response:

$numbers=['10','-2','-1','8','-7','1','-2','-3'];

   $i=0;
   // there is no need initializing sum here since you it will be the first number
   $sum=0;    
    
    while ($i < count($numbers)){
        
   //  $sum=$sum $numbers[$i]; This is not needed
    
   if ($numbers[$i] > 0) {
      // if the $numbers[$i] is greater than 0 then it is a positive number
      // you set $sum to the new positive number
        $sum = $numbers[$i];
    } else {
      //else you perform arithmetic function here 
      // and since $numbers[$i] is a negetive number adding it will substract from $sum
        $sum  = $numbers[$i];
    }
   //  You're concern about the sum so you should do your logic before echoing 
      echo $sum; 
   // Always remember to increment as while loop wont do that for you        
      $i  ;
   }
  • Related