1

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

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Aman
  • 13
  • 2
  • 1
    I would approach it the same way. But your naming is not ideal. `$str = 0;` should be named something else. Like: `$sum = 0;` Also like others have said PHP has a build in function to sum up array values. – Roland Starke Nov 12 '17 at 07:16
  • 1
    If someone tells you the solution is bad but refuses to tell you _why_ it is bad, that's pretty sad. At any rate, if you are looking for qualitative judgements on your code and suggestions for improvements, you might want to try codereview.stackexchange.com. – Ray Toal Nov 12 '17 at 07:17

2 Answers2

0

you should use array_sum(explode(",",$yourarray)) after exploding the string rather than looping array . this would be more efficient.

Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
0

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));
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35