Home > Back-end >  why is my array_sum showing the wrong number?
why is my array_sum showing the wrong number?

Time:05-21

I have this array and I want to add the values:

$sustainCapital_arr = Array ( [0] => 2,759 [1] => 3,269 [2] => 3,481 [3] => 3,573 [4] => 3,997 [5] => 4,421 [6] => 10,999 )

now, interestingly array_sum is giving me an incorrect number:

$total_Sustaining = array_sum($sustainCapital_arr);     output: 28 ???

Output should be 32,499.

Now, I also tried to use a foreach loop and the same happens. What the hell is going on here?

$total_Sustaining = 0;
foreach ($sustainCapital_arr as $key=>$value){
                            
   $total_Sustaining  = $value;
}

output is again 28!!!

What am I doing wrong here?

CodePudding user response:

$total_Sustaining = 0;
foreach ($sustainCapital_arr as $key=>$value){
                            
   $total_Sustaining  = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
}

CodePudding user response:

Looks like everything is okay and working in my case with the same value, but in your array I see (,) in between digits which invalidates being an integer value try this out

$sustainCapital_arr = [2759, 3269, 3481,3573,3997,4421,10999];
echo array_sum($sustainCapital_arr);
  • Related