0

I want all of the elements in the array to be added together, but this doesn't seem to be working.

    <?php

    function mimic_array_sum($array) {
        foreach($array as $total) {
            $total = $total + $total;
        }
        return $total;
    }
    $var = array(1,2,3,4,5);
    $total = mimic_array_sum($var);
    echo $total;
?>
4

6 回答 6

2

$total = $total + $total--> 好吧,那是你的问题...

$total变量在通过数组的每个循环中被覆盖。为数组中的每个数字分配一个单独的变量,如下所示:

function mimic_array_sum($array) {
    $total = 0;
    foreach($array as $number) {
        $total = $total + $number;
    }
    return $total;
}
$var = array(1,2,3,4,5);
echo mimic_array_sum($var);

尽管我不清楚这一点...您不妨使用php-function array_sum ...

$var = array(1,2,3,4,5);
echo array_sum($var);
于 2013-09-07T17:40:06.620 回答
1
$var = array(1,2,3,4,5);
$total = array_reduce(
    $var,
    function($sum, $value) {
        return $sum + $value;
    }
);

虽然为什么不简单地使用array_sum()?

于 2013-09-07T17:40:13.863 回答
1

您可以使用array_sum — 计算数组中值的总和

$var = array(1,2,3,4,5);
$total = array_sum($var);
echo $total;
于 2013-09-07T17:53:16.767 回答
0
<?php
$a = array(1,2,3,4,5);
echo "sum is:".array_sum($a);
?>

手册

于 2013-09-07T17:41:44.330 回答
0
  <?php

    function mimic_array_sum($array) {
            $total = 0;
        foreach($array as $elem) {
            $total += is_numeric($elem) ? $elem : 0;
        }
        return $total;
    }
    $var = array(1,2,3,4,5);
    $total = mimic_array_sum($var);
    echo $total;
?>
于 2013-09-07T17:39:35.063 回答
0

请尝试以下操作,您必须使用单独的变量才能这样做。否则你可以使用array_sum()

function mimic_array_sum($array) {
    $test = 0;
    foreach($array as $total) {
        $test = intval($test) + intval($total);
    }
    return $test;
}
$var = array(1,2,3,4,5);
$total = mimic_array_sum($var);
echo $total;

?>

于 2013-09-07T17:40:45.857 回答