计算数组中整数的总和

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

How to calculate the sum of integers from arrays

问题

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

我创建了一个空数组

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

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

  1. foreach ($arr as $val){
  2. if(is_int($val)){
  3. array_push($arr2, $val);
  4. }
  5. }

然后我对所有整数求和

  1. $sum=0;
  2. foreach($arr2 as $val2){
  3. $sum += $val2;
  4. }
  5. 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

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

I found an empty integer and pushed into empty array

  1. foreach ($arr as $val){
  2. if(is_int($val)){
  3. array_push($arr2, $val);
  4. }
  5. }

and then i summed all integer

  1. $sum=0;
  2. foreach($arr2 as $val2){
  3. $sum += $val2;
  4. }
  5. echo $sum;

Is my way correct?

答案1

得分: 1

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

  1. $arr = array(14, 13, "Cat", 16, "Dog", 13.8, 14.5);
  2. $arr2 = array_filter($arr, 'is_int');
  3. $sum = array_sum($arr2);
  4. 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:

  1. $arr = array(14, 13,"Cat",16,"Dog", 13.8, 14.5);
  2. $arr2 = array_filter($arr, 'is_int');
  3. $sum = array_sum($arr2);
  4. 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:

确定