db->table('homework'); $builder->select('score') ->where('student_id', $studentId) ->where('semester', $semester) ->where('school_year', $schoolYear); if ($classSectionId !== null) { $builder->where('class_section_id', $classSectionId); } $rows = $builder->get()->getResultArray(); if (empty($rows)) { return null; } $totalScore = 0.0; $scoreCount = 0; foreach ($rows as $row) { $score = $row['score'] ?? null; if ($score === null || (is_string($score) && trim($score) === '') || $score === '' || !is_numeric($score)) { continue; } $totalScore += (float) $score; $scoreCount++; } if ($scoreCount === 0) { // All entries are blank/null return null; } return round($totalScore / $scoreCount, 2); } }