计算数组中整数的总和

huangapple go评论63阅读模式
英文:

How to calculate the sum of integers from arrays

问题

我在想是否有其他方法来计算整数的总和。是否有内置函数或不同的计算方法?

我创建了一个空数组

$arr=array(14, 13,"Cat",16,"Dog", 13.8, 14.5);
$arr2=array();

我找到了一个空的整数并将其推入空数组

foreach ($arr as $val){
    if(is_int($val)){
        array_push($arr2, $val);
    } 
}

然后我对所有整数求和

$sum=0;
foreach($arr2 as $val2){
    $sum += $val2;
}
echo $sum;

我的方法正确吗?

英文:

I'm wondering if there is another way to calculate the sum of integers. Are there any built-in functions, or different ways to count this?

I create an empty array

$arr=array(14, 13,"Cat",16,"Dog", 13.8, 14.5);
$arr2=array();

I found an empty integer and pushed into empty array

foreach ($arr as $val){
    if(is_int($val)){
        array_push($arr2, $val);
    } 
}

and then i summed all integer

$sum=0;
foreach($arr2 as $val2){
    $sum += $val2;
}
echo $sum;

Is my way correct?

答案1

得分: 1

你计算这些整数的方式基本上没问题。查看php-docs中的array_filter()和array_sum()函数,以摆脱这些foreach循环:

$arr = array(14, 13, "Cat", 16, "Dog", 13.8, 14.5);
$arr2 = array_filter($arr, 'is_int');
$sum = array_sum($arr2);
echo $sum;
英文:

Your way of calculating the sum of these integers is basically okay.
Take a look at array_filter() and array_sum() function in the php-docs to get rid of these foreach-loops:

$arr = array(14, 13,"Cat",16,"Dog", 13.8, 14.5);
$arr2 = array_filter($arr, 'is_int');
$sum = array_sum($arr2);
echo $sum;

huangapple
  • 本文由 发表于 2023年4月13日 22:23:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76006575.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定