使用PHP在数组中添加数字

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;
?>

$total = $total + $total --> well, there's your problem...

The $total variable gets overwritten on each loop through the array. Assign a separate variable for each number in the array, like so:

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);

Although the point of this is not clear to me... You might as well use the php-function array_sum...

$var = array(1,2,3,4,5);
echo array_sum($var);
  <?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;
?>
$var = array(1,2,3,4,5);
$total = array_reduce(
    $var,
    function($sum, $value) {
        return $sum + $value;
    }
);

though why not simply use array_sum()?

Please try following, you have to take separate variable to do so. Or else you can use 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;

?>

<?php
$a = array(1,2,3,4,5);
echo "sum is:".array_sum($a);
?>

See Manual

You can use array_sum — Calculate the sum of values in an array

$var = array(1,2,3,4,5);
$total = array_sum($var);
echo $total;