Zestyy99
Zestyy99

Reputation: 307

Using an associative array to calculate an average grade

If I have an average score of:

$average = 95.00000000

And I have an array:

$grades = array("91-100"=>"A+","80-89"=>"A","70-79"=>"B","60-69"=>"C","50-59"=>"D","0-49"=>"F");

When I try to get an average grade by doing:

$grade = $grades[$average];

I get an error:

Notice: Undefined index: 95.00000000

I think the issue comes from the the key's of the array, but is there a way to do what i'm trying to achieve?

Upvotes: 0

Views: 1100

Answers (2)

Bogdans
Bogdans

Reputation: 169

I would suggest changing the grade array to a simpler structure, thus you would get a simpler and more predictable code

<?php
$average = 95.00000000;
$grades = array(
    array(
        'grade' => 'A+',
        'max' => 100,
        'min' => 90
    ),
    array(
        'grade' => 'A',
        'max' => 89,
        'min' => 80
    ),
    array(
        'grade' => 'B',
        'max' => 79,
        'min' => 70
    ),
    array(
        'grade' => 'C',
        'max' => 69,
        'min' => 60
    ),
    array(
        'grade' => 'D',
        'max' => 59,
        'min' => 50
    ),
    array(
        'grade' => 'F',
        'max' => 49,
        'min' => 0
    ),
);

$result = null;
$averageScore = (int) floor($average); // it's better to compare int to int instead of float to int
foreach($grades as $grade) {
    if ($average < $grade['max'] && $average >= $grade['min']) {
        $result = $grade['grade'];
        break;
    }
}
if ($result !== null) {
    echo 'Your grade is: ' . $result;
} else {
    echo 'Grading error, please ask your professor for details!';
}

Upvotes: 0

Syscall
Syscall

Reputation: 19764

You have to iterate over the keys, and check if your value is between them :

$grades = array("91-100"=>"A+","80-89"=>"A","70-79"=>"B","60-69"=>"C","50-59"=>"D","0-49"=>"F");
$average = 95.00000000 ;

$grade = '' ;
foreach ($grades as $val => $cur_grade) {
    list($min, $max) = explode('-', $val); // split key into min and max
    if ($average >= $min && $average <= $max) { // compare
        $grade = $cur_grade ; // get the value
        break ; // stop the loop
    }
}
echo $grade ;

Will outputs :

A+

Note that if your $average is not in the range (ex. 69.9), it will match will no case. So you could use "90-100", "80-90", ...

$grades = array("90-100"=>"A+","80-90"=>"A","70-80"=>"B","60-70"=>"C","50-60"=>"D","0-50"=>"F");
$average = 69.9 ;
// ..code above..
echo $grade ; // Outputs "C"

And

$average = 70.0 ;
// ..code above..
echo $grade ; // Outputs "B"

Upvotes: 4

Related Questions