0

I have an array like this $arr = array(2, -3, 6, 1);

And I only want to select the positive numbers to be able to sum the others between them.

So I wrote this code, but I'm a bit lost on how to select the elements I only want to do something with them, like summing them.

$sum = implode(",", $arr);

  for($i = 0; $i <= strlen($sum); $i++) {
    if($i <= 0) {
    } else {
      return explode(",", array_sum($i));
  }
 }
}
3
  • What do you mean by "select"? Commented Jan 13, 2017 at 15:12
  • use array_filter, no need to use an explicit loop: php.net/manual/en/function.array-filter.php Commented Jan 13, 2017 at 15:12
  • @GrumpyCrouton I edited the title. Sorry about that, I just want to be able to select only element I want in the array. And sum the others together. Commented Jan 13, 2017 at 15:16

3 Answers 3

4

Use array_fliter to filter the value, and array_sum to sum the array.

   array_sum(array_filter($array, function($v){return $v>0;});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. But I can't figure out how does that works. I have $arr = array(2, -3, 6, 1);
0

Use array_filter with callback function like below :

<?php
    $arr = array(2, -3, 6, 1);
    function positive($a){
        if($a > 0){
            return $a;
        }

    }
    $newArr = array_sum(array_filter($arr, "positive"));
    print_r($newArr);
?>

Comments

0

Using array_reduce:

$arr = array(2, -3, 6, 1);

$result = array_reduce($arr, function($c, $i) { return $i > 0 ? $c + $i : $c; });

echo $result;

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.