Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 963
Patrioticcow Avatar asked Jun 13 '12 23:06

Patrioticcow


1 Answers

$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().

like image 157
Decent Dabbler Avatar answered Oct 09 '22 19:10

Decent Dabbler