PHP数组中只求正数的和

PHP数组中只求正数的和,php,arrays,add,Php,Arrays,Add,首先,谢谢你看我的问题 我只想使用if,else语句将$number中的正数相加 $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.) $numbers=数组(1,8,12,7,14

首先,谢谢你看我的问题

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

$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.)
$numbers=数组(1,8,12,7,14,-13,8,1,-1,14,7);
$total=0;
如果($数字<0{
$numbers=0;
}
elseif(现在我只希望在$total中加上正数。)
我是一名一年级的学生,我正在努力理解其中的逻辑

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

$total = 0;

foreach($numbers as $number)
{
  if($number > 0)
    $total += $number;
}
这将遍历数组的所有元素(foreach=数组中的每个数字),并检查元素是否大于0,如果大于0,则将其添加到
$total


这将遍历数组的所有元素(foreach=数组中的每个数字)检查元素是否大于0,如果大于0,则将其添加到
$total

我不会给出直接答案,但这里的方法是需要一个简单的循环,可以是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
    }
}
或者正如michael在评论中所说,函数也可以用于此目的:

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

我不会给出直接的答案,但这里的方法是你需要一个简单的循环,可以是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
    }
}
或者正如michael在评论中所说,函数也可以用于此目的:

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

不需要循环。组合和不需要循环。组合和foreach,当然。谢谢你的时间和财力foreach,当然。谢谢你的时间和财力。我喜欢你为什么向我解释这一点,谢谢!我现在明白逻辑了。@Greenie当然,我很高兴这一点light@Greenie顺便说一句,别忘了接受上面的答案我,第一个得到答案的人,点击他答案左边的复选框。接受就是关心:)我喜欢你为什么向我解释这个,谢谢!我现在明白逻辑了。@Greenie当然,我很高兴这一点light@Greenie顺便说一下,别忘了接受我上面的答案,第一个得到的答案,点击他答案左边的复选框。接受就是关心:)