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 )
2
  • $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. Commented Apr 15, 2015 at 18:06
  • I prefer to use var_dump insted of print_r that shows types properly Commented Apr 15, 2015 at 18:07

4 Answers 4

3

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

$exploded =  explode ( "," , $amount_array);
var_dump($exploded);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.