Search code examples
phparray-sum

php array_sum returning first value only


I'm fairly new at php, but this seems to be me overlooking something completely basic?

I have some values in a database column, that are comma separated like so: 1,2,3

When I try to get the sum of the values, I expect the echo of array_sum to be 6, but I only get returned the first value ie. "1"

echo $amount; //Gives 1,2,3 etc.

$amount_array = array($amount);
echo array_sum($amount_array); //Only prints "1"

print_r($amount); // shows 1,2,3
print_r($amount_array); // shows Array ( [0] => 1,2,3 )

Solution

  • It's a string not an array, you have to split it using explode function:

    $exploded =  explode ( "," , $amount_array);
    var_dump($exploded);