how to do a sum on a string in php?(如何在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().
这篇关于如何在php中对字符串进行求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在php中对字符串进行求和?
基础教程推荐
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
