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