SUM OF数字高于0

时间:2014-02-12 15:47:29

标签: php

我正在做作业,我尝试过这个代码,但似乎不太好,我的作业是获得高于0的数字总和。

<?PHP
$b=array (1,2,-3,0,7,25,0,42,1,-10);
$s=0; $BUB=0; 
for($BUB=0;$BUB=10;$BUB++)
{
    if($b>0){
        $s=$s+$b;} [$bub=0];
        $BUB++;

}
echo "suma je $s" ;

?>

2 个答案:

答案 0 :(得分:1)

$b=array (1,2,-3,0,7,25,0,42,1,-10);

$r = array_sum(
    array_filter(
        $b,
        function ($value) {
            return $value > 0;
        }
    )
);
var_dump($r);

$b=array (1,2,-3,0,7,25,0,42,1,-10);

$r = array_reduce(
    $b,
    function($adder, $value) {
        return $adder += ($value > 0) ? $value : 0;
    }
);
var_dump($r);

答案 1 :(得分:0)

$sum = 0;
foreach(array (1,2,-3,0,7,25,0,42,1,-10) as $num) {
  if($num > 0) {
    $sum += $num;
  }
}