how to do a sum on a string in php?

前端 未结 5 1037
忘掉有多难
忘掉有多难 2021-01-18 14:58

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

相关标签:
5条回答
  • 2021-01-18 15:33

    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. (:

    0 讨论(0)
  • 2021-01-18 15:35
    function get_sum()
    {
        global $v;
        $temp=0;
        for($i=0;$i<strlen($v);$i++)
        {
            $temp+=intval($v[$i]);
        }
        echo $temp;
    }
    
    echo get_sum();
    
    0 讨论(0)
  • $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().

    0 讨论(0)
  • 2021-01-18 15:50
    $v = "24000,1500,1500,1500,1500,1500,";
    $result = 0;
    foreach(explode(',',$v) as $val)
         $result +=intval($val);
    
    echo $result;///31500
    
    0 讨论(0)
  • 2021-01-18 15:56

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

    0 讨论(0)
提交回复
热议问题