Patrioticcow Patrioticcow - 13 days ago 4
PHP Question

how to do a sum on a string in php?

i have a simple question:

i have this var:

$v = "24000,1500,1500,1500,1500,1500,";


i would like to add those numbers together.

i've tried to
str_replace
the
,
with
+
and so a
eval()
, but that didn't worked.

i also tried
str_split()
but it doesn't know to split on the
,
.

maybe if somehow convert it to an array and do a
array_sum
...

any ideas?

thanks

Answer
$sum = array_sum( explode( ',', $v ) );

What this does is split $v by the delimiter , with explode() and sum the resulting array of parts with array_sum().

Comments