2014-09-28 66 views
1

首先,感谢您查看我的问题。总结PHP数组中只有正数

我只想使用if,else语句在$数字中加上正数。

$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.) 

我是第一年级学生,我想了解逻辑。

+2

没有需要循环。 ['array_filter()'](http://us1.php.net/manual/en/function.array-filter.php)和['array_sum()'](http://us1.php。 net/manual/en/function.array-sum.php) – 2014-09-28 12:32:53

回答

2
$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,如果是,将其添加到$total

+0

foreach,offcourse。感谢您的时间和负担 – Greenie 2014-09-28 12:40:59

3

I” m不会给出直接的答案,但是这里的方法是需要一个简单的循环,可以是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 
    } 
} 

或者像迈克尔在评论中说,功能也可以在此目的而使用:

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

我喜欢你为什么向我解释这个,谢谢!我现在看到了逻辑。 – Greenie 2014-09-28 12:44:46

+0

@Greenie确定我很高兴这样流出一些光 – Ghost 2014-09-28 12:45:54

+1

@Greenie顺便说一句,不要忘记接受我上面的答案,先拿到答案,点击答案左边的那个检查。接受是关怀:) – Ghost 2014-09-28 12:49:32