如何在PHP中对逗号分隔的数字字符串求和?
我想要所有字符串的总和,像这样如何在PHP中对逗号分隔的数字字符串求和?,php,Php,我想要所有字符串的总和,像这样1+2+3+4+5 $input = '12345'; 使用以下代码: <?php $input = '1,2,3,4,5'; $res = explode(',',$input); foreach($res as $row) { $result += $row; } echo "Total :". $result; //OR echo array_sum($res); Demo:您可以通过PHP的array\u sum函数来实现这一点 $inp
1+2+3+4+5
$input = '12345';
使用以下代码:
<?php
$input = '1,2,3,4,5';
$res = explode(',',$input);
foreach($res as $row)
{
$result += $row;
}
echo "Total :". $result;
//OR
echo array_sum($res);
Demo:您可以通过PHP的
array\u sum
函数来实现这一点
$input = '1,2,3,4,5';
$res = explode(',',$input);
$result = array_sum($res);
echo $result;
首先,您需要替换该
,
,然后简单地像
$input = str_replace(",","",'1,2,3,4,5');
$value = 0;
$i = 0;
while(isset($input[$i]))
{
$value += $input[$i];
$i++;
}
echo $value;
$input = str_replace(",","",'1,2,3,4,5');
$value = 0;
$i = 0;
while(isset($input[$i]))
{
$value += $input[$i];
$i++;
}
echo $value;