仅对 PHP 数组中的正数求和

1 php arrays add

首先,感谢您看我的问题。

我只想使用 if,else 语句将 $numbers 中的正数相加。

$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);

$total = 0;

if ($numbers < 0 {
    $numbers = 0;
}
elseif (now i want only the positive numbers to add up in the $total.)
Run Code Online (Sandbox Code Playgroud)

我是一年级的学生,我正在努力理解其中的逻辑。

Kev*_*vin 5

我不会给出直接的答案,但这里的方式是你需要一个简单的循环,可以是 for 或 foreach 循环,所以每次迭代你只需要检查循环中的当前数字是否大于零。

例子:

$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);
$total = 0;
foreach($numbers as $number) { // each loop, this `$number` will hold each number inside that array
    if($number > 0) { // if its greater than zero, then make the arithmetic here inside the if block
        // add them up here    
        // $total 
    } else {
       // so if the number is less than zero, it will go to this block
    }
}
Run Code Online (Sandbox Code Playgroud)

或者正如迈克尔在评论中所说,一个函数也可以用于这个目的:

$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);
$total = array_sum(array_filter($numbers, function ($num){
    return $num > 0;
}));
echo $total;
Run Code Online (Sandbox Code Playgroud)