6

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

Patrioticcow
  • 26,422
  • 75
  • 217
  • 337
  • [Without delimiting characters](https://stackoverflow.com/questions/3232511/get-the-sum-of-all-digits-in-a-numeric-string) – mickmackusa Jul 11 '22 at 22:03

5 Answers5

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

Decent Dabbler
  • 22,532
  • 8
  • 74
  • 106
4
$v = "24000,1500,1500,1500,1500,1500,";
$result = 0;
foreach(explode(',',$v) as $val)
     $result +=intval($val);

echo $result;///31500
richie-torres
  • 746
  • 1
  • 8
  • 29
1

Use str_getcsv to obtain an array of the values. Then loop through the array to sum those values.

Nabeel
  • 557
  • 4
  • 15
1

The explode function works best in your situation. What explode 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. (:

bryan.blackbee
  • 1,934
  • 4
  • 32
  • 46
-1
function get_sum()
{
    global $v;
    $temp=0;
    for($i=0;$i<strlen($v);$i++)
    {
        $temp+=intval($v[$i]);
    }
    echo $temp;
}

echo get_sum();
Shiro
  • 7,344
  • 8
  • 46
  • 80
  • Can I suggest explaining the working parts of this answer so the person asking the question understands how it works/what it is. And how to use it. – Danny Staple Sep 20 '18 at 14:46