0

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 )
Mohammad
  • 21,175
  • 15
  • 55
  • 84
Mark
  • 33
  • 10
  • $amount is a string. you're then stuffing that string into an array - that string becomes a SINGLE entry in the array. php won't magically split the string up into multiple components and make each of those components an array element... you need explode() for taht. – Marc B Apr 15 '15 at 18:06
  • I prefer to use `var_dump` insted of `print_r` that shows types properly – Alex Apr 15 '15 at 18:07

4 Answers4

3

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

$exploded =  explode ( "," , $amount_array);
var_dump($exploded);
Jafar Akhondali
  • 1,552
  • 1
  • 11
  • 25
2

To use the array_sum the string needs to be converted to an array

You need to use the explode function:

$amount_array = explode(',', $amount);

So you total code should be like this:

$amount_array = explode(',', $amount);
echo array_sum($amount_array);
Perry
  • 11,172
  • 2
  • 27
  • 37
2

array_sum() works by adding up the values in an array. You only have one key=>value pair in your array: key 0 with a value of 1,2,3.

If you have a comma-separated list, and want that to be an array, I would use the explode() function to turn the list into the proper key=>value pairs that array_sum() would expect.

Try

$amount_array = explode(',',$amount);
David Wyly
  • 1,671
  • 1
  • 11
  • 19
1

You can not initialize an array the way you intend. You are passing in a comma-separated string, which is just a single argument. PHP doesn't automagically convert that string into separate arguments for you.

In order to convert a comma-separated string into an array of individual values you can break up the string with a function like explode(), which takes a delimiter and a string as its arguments, and returns an array of the delimiter-separated values.

$amount_array = explode( ',', $amount ); // now $amount_array is the array you intended
Decent Dabbler
  • 22,532
  • 8
  • 74
  • 106