Search code examples
phpstringsumdelimited

$str = "1,2,3,4,5,6,7"; How to get the sum of values?


I was asked this question in a PHP test,

Question: How to get the sum of values?

$str = "1,2,3,4,5,6,7";

My Solution was:

// Splitting numbers in array and adding them up
$str = "1,2,3,4,5,6,7";
$num_array = explode(',', $str);

$str = 0;
foreach($num_array as $num) {
    $str+=$num;
}
echo $str;

I was told that my solution is BAD, is it BAD? Can anyone please tell why is it BAD? And any better/best solutions?

Thanks, in advance


Solution

  • Well, your solution is correct, but they might be expecting optimized or efficient or smallest code. May be like this:

    $str = "1,2,3,4,5,6,7";
    echo array_sum(explode(',', $str));