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
Use str_getcsv to obtain an array of the values. Then loop through the array to sum those values.
The
explode
function works best in your situation. Whatexplode
does is that it splits the string based on the parameter that you specify it. You can think of it as slicing the string based on the parameter and putting it in an array.Once done, you have a bunch of numbers in the array. Just do a sum. If you want to ensure that all are numbers, you can use is_numeric() to ensure. (:
What this does is split
$v
by the delimiter,
withexplode()
and sum the resulting array of parts witharray_sum()
.