英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论