-3

I need to get the total value of this array of all the numbers above or equal to 0. This is the array

$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983); 

This is the code i have so far, but it only shows the highest number of the array and doesnt count the values up and shows the total.

$totaal = 0;
      for($y=0; $y < count($aReeks); $y++)
      {
          if($totaal < $aReeks[$y] && $aReeks[$y] > 0)
          $totaal = $aReeks[$y];
      }

I have to do it with a for loop.

3 Answers 3

2

Here's a quick way:

$total = array_sum(array_filter($aReeks, function($n) { return $n > 0; }));
  • Filter the array for values greater than 0
  • Sum that array

Oh I now see the "I have to do it with a for loop.", so this won't be accepted for your homework I imagine.

Sign up to request clarification or add additional context in comments.

Comments

1
$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983); 

$total=0;
for($i =0 ; $i< count($aReeks) ; $i++)
{
if($aReeks[$i]>=0)
{
    $total+= $aReeks[$i];
}
}
echo $total ;
?>

Output

11859

1 Comment

If the answer is helpful ,then accept it .So that it may be helpful for others.
0

You are making 2 major mistakes one is in if condition which is $totaal < $aReeks[$y] you don't need this check at all. Secondly rather than summing up the value of each item to the total of all previous items... you are simply assigning the value to the $totaal variable inside the loop.

$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983); 
$totaal = 0;
for($y=0; $y < count($aReeks); $y++)
{
    if($aReeks[$y] > 0)
        $totaal = $totaal + $aReeks[$y];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.