【问题标题】:How to add an array together without using array_sum [duplicate]如何在不使用array_sum的情况下将数组添加在一起[重复]
【发布时间】:2019-10-15 07:54:59
【问题描述】:

我正在尝试学习 PHP,并且我正在尝试通过长期做事来做到这一点。 所以我遇到了array_sum(),我想知道是否有一种方法可以不使用它来计算数组。

例如

$my_array = array(10, 80, 30);

我只做到了这一点,我被难住了。我在谷歌上看过,但我没有找到任何东西。

$implode = implode(",", $my_array );

$explode = explode(",", $implode);

foreach($explode as $test)
{


 }

【问题讨论】:

  • 您是否有任何具体原因要这样做?
  • $my_array 与$explode 相同。你能告诉我们你想做什么吗?
  • 只是为了让我学习和理解
  • 只要有本机功能,就使用它。因为优化了。不要再发明轮子了。

标签: php


【解决方案1】:

我会一直选择原生函数,因为它们已经过优化和测试。[所以基本上我想说的是使用 array_sum()],

除了上面之外,下面是foreach() 对一维数组的所有值求和的过程[仅供参考]

<?php


$result = 0; //create a variable with 0 value
foreach($explode as $test)
{
  $result += $test; //add array value to the newly created value

}

echo $result; //print final sum of all array values

输出:-https://3v4l.org/0qMJu

注意:- 请阅读@Markus Zeller 问题下的评论

【讨论】:

  • 就是这样,非常感谢。
  • @KittyKat 很高兴为您提供帮助。请再次阅读我的回答。我也添加了一些注释以及解释。
猜你喜欢
  • 2017-03-29
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-24
  • 2016-06-02
相关资源
最近更新 更多