How to get a grade and transform it into a letter grade in PHP

1 Answer

0 votes
function toLetterGrade(float $score): string {
    // Define score thresholds and grades
    $scores = [95.0, 90.0, 85.0, 80.0, 75.0, 70.0, 65.0, 60.0];
    $grades = ["A+", "A", "B+", "B", "C+", "C", "D+", "D"];

    // Iterate through scores and find the grade
    $count_scores = count($scores);
    for ($i = 0; $i < $count_scores; $i++) {
        if ($score >= $scores[$i]) {
            return $grades[$i];
        }
    }

    return "F"; // Default grade if none of the scores match
}

// Test the program with individual scores
echo toLetterGrade(95) . PHP_EOL; // A+
echo toLetterGrade(90) . PHP_EOL; // A
echo toLetterGrade(80) . PHP_EOL; // B
echo toLetterGrade(60) . PHP_EOL; // D
echo toLetterGrade(50) . PHP_EOL; // F


  
/*
run:
      
A+
A
B
D
F

*/

 



answered Mar 23, 2025 by avibootz
edited Mar 23, 2025 by avibootz

Related questions

2 answers 130 views
1 answer 82 views
1 answer 90 views
1 answer 108 views
2 answers 135 views
2 answers 106 views
...