I've a function in php, this is the function
public function actionGetTotal($id){
$month = date('m');
$year = date('Y');
$arrayDataMitra = Yii::$app->db->CreateCommand("SELECT nilai FROM data WHERE MONTH(first_date) = '$month' AND YEAR(first_date) = '$year' AND idMitra = '$id' AND idProgram BETWEEN '7' AND '11'")->queryAll();
$arrayNilai = array_column($arrayDataMitra, 'nilai');
$countArr = count($arrayNilai);
$totalPoin = 0;
for($i = 0; $i < $countArr; $i++){
$totalPoin = $totalPoin + $arrayNilai[$i];
}
$totalPoin = $totalPoin / $countArr; //issue
return $totalPoin;
}
if I printout as echo $totalPoin . ', ' . $countArr; die();
it will show 4, 2. But if I delete it, the function return Division by zero. It said the $countArr is 0. Anyone can explain why it happen?
Thanks
Update
If I do
$countArr = count($arrayNilai);
echo '<pre>';
echo 'This is data array';
echo '<br>';
print_r($arrayNilai);
echo '<br>';
echo 'This is array count';
echo '<br>';
echo $countArr;
die();
it return
This is data array
Array
(
[0] => 2
[1] => 2
)
This is array count
2
UPDATE I think it's not the function logic error. I'm using Yii2 framework, and that function called inside the gridview in index.php. The cause is I've 3 rows of data where only a row that contain data. That's why the
$countArr
is 0, because in second row there is no data from the$arrayNilai
. Thankyou
Well if the query return no data. It leads to division by zero. What would you expect the result to be in such case? Maybe zero? You have to handle this situation explicitly. Like
if ($countArr===0) return 0;
Or dont call the entire function at all, if there is no data.
What do you mean by 4,2. It will be 4 or 2. I think you had miss here to concatinate like $totalPoin = $totalPoin + $arrayNilai[$i];
will be $totalPoin .= $totalPoin + $arrayNilai[$i];
try to handle error handling here. You can do by using @ with variable name.