如何在php中的数组中添加特定数字[关闭]
问题描述:
$a = array(2, 6, 24, 16, 7, 10);
I know how to add all the numbers using array_sum()
but if I want to add only the numbers between 2
and 16
how can do that?
This is one of the solution that that I've come up with:
$a = array(2, 6, 24, 16, 7, 10);
$r = array_slice($a, 0, -2);
print_r (array_sum($r));
Just want to know if there is any other way to get the result.
$ a = array(2,6,24,16,7,10);
pre>
我知道如何使用 array_sum() code>添加所有数字但是如果我只想添加 2 code之间的数字 >和 16 code>怎么做? p>
这是我提出的解决方案之一: p>
$ a = array(2,6,24,16,7,10);
$ r = array_slice($ a,0,-2);
print_r(array_sum($ r));
code> pre>
只想知道是否有其他方法可以获得结果。 p>
div>
答
To deal with dynamic bound limits you can extend the initial approach(array_slice
+ array_sum
) using array_search
function:
$arr = [2, 6, 24, 16, 7, 10];
$a = 10;
$b = 24;
$lowerBound = array_search($a, $arr);
$upperBound = array_search($b, $arr);
if (($low = $lowerBound) > $upperBound) { // if bounds were confused
$lowerBound = $upperBound;
$upperBound = $low;
}
$sum = array_sum(array_slice($arr, $lowerBound, $upperBound - $lowerBound + 1));
print_r($sum); // 57