如何在php中对字符串进行求和?
我有一个简单的问题:
我有这个变量:$v = "24000,1500,1500,1500,1500,1500,";
我想把这些数字加在一起.
i would like to add those numbers together.
我尝试用 + 等 eval() 替换 str_replace ,,但是没用.
i've tried to str_replace the , with + and so a eval(), but that didn't worked.
我也试过 str_split() 但它不知道在 , 上分割.
i also tried str_split() but it doesn't know to split on the ,.
也许如果以某种方式将其转换为数组并执行 array_sum...
maybe if somehow convert it to an array and do a array_sum...
有什么想法吗?
谢谢
推荐答案
$sum = array_sum( explode( ',', $v ) );
这样做是将 $v 用分隔符 , 和 分开explode() 并将结果数组与 array_sum().
What this does is split $v by the delimiter , with explode() and sum the resulting array of parts with array_sum().
相关文章