0

I have seen read other posts that are almost similar to my problem. but I can't find the right answer to my problem. here I have a $data[4] array that is like the following.

Array ( [0] => 0.84 ) Array ( [0] => 2.79 ) 

and this my php code for calculating the value in variable $data[4]

$a= array();
foreach(array($data[4]) as $datas) {
    $a[] = $datas;
}
 print_r($a); 

 $sum = array_sum($a);
 echo $sum;

}

but the results are not calculating, instead of displaying values ​​from the data array $data[4] like this

0.84
2.79
Ram Chander
  • 1,088
  • 2
  • 18
  • 36
yagami cell
  • 147
  • 12

2 Answers2

0

You got two arrays with 0 index in $data[4]. You have to flatten this $a, you can add extra foreach.

$a= array();
foreach(array($data[4]) as $datas) {
    foreach($datas as $item) { // here - extra foreach
        $a[] = $item;
    }
}
 print_r($a); 

 $sum = array_sum($a);
 echo $sum;

}

By the way - consider using var_export to show more precisely what's in your data :)

PatNowak
  • 5,721
  • 1
  • 25
  • 31
  • not working i got eror code Message: Invalid argument supplied for foreach() and i done use var_export , this array data in var_export = array ( 0 => '0.84', )array ( 0 => '2.79', ) – yagami cell Feb 25 '20 at 09:03
0

Assume that your array is like $data[4] = [[0.89],[2.79]] then you can use this code to get sum.

$sum = 0;
foreach($data[4] as $datas) {
    $sum +=  array_sum($datas);
}
echo $sum;