dInGd0nG
dInGd0nG

Reputation: 4114

PHP upgrade grades

I have two arrays; $marks and $grades. $marks contain mark scored by a student and $grades is obtained by looping through $marks using the following function.

 function convertMarkToGrade($mark)
    {
        if($mark<21)
            return "D";
        else if($mark<33)
            return "C";
        else if($mark<41)
            return "B";
        else if($mark<=50)
            return "A";
    }

The problem is i want to upgrade the smallest and second smallest grades in $grades array using the following criteria

  1. Upscaling is done from lowest grade to next higher grade and so on ie B to A, C to B etc

  2. In case of tie in Grades the grade with highest mark is upgraded.

For example:
Let $marks be array(25,43,36,16,28). So we get $grades as array("C","A","B","D","C"). i want to generate a $upgraded_grades =array("C","A","B","C","B") ie the D grade (the smallest grade) is upgraded and the C grade(second smallest grade but with maximum marks) is also upgraded.

How can I do it in php?

Upvotes: 0

Views: 218

Answers (2)

Shubham
Shubham

Reputation: 22307

You can use Associative arrays. Here is a one of the method:

Edited:

//create associative array that has values as array of marks
$grades_arr = array("D" => array(), "C" => array(), "B" => array(), "A" => array() );

for($i = 0;$i < count($grades);$i++)
    array_push($grades_arr[$grades[$i]], $marks[$i]);

$loop = 0;
foreach($grades_arr as $key => &$value){
    if(empty($value))
        continue;

    if($loop == 2)
        break; //break after two upgrades
    else{
        $max = max($value);
        //unset the variable
        $value = array_diff($value, array($max));
        $value = array_values($value); 
        //push it into next higher grade
        array_push($grades_arr[chr(ord($key)-1)], $max);
        $loop++;
    }
}

print_r($grades_arr);

Upvotes: 2

Jovan Perovic
Jovan Perovic

Reputation: 20193

If I understand you correctly you need this:

    $letterMark = ....; // "A","B","C" or "D"

    /* decrese number, that is increse letter by one
       but make sure it does not exceed 'A' mark 
    */
    $ordedMark = max(ord($letterMark)- 1, ord('A')); 
    $upscaledMark = chr($ordedMark);

    return $upscaledMark;

I wrapped this snippet into function here: http://codepad.viper-7.com/i9Rtgi

Upvotes: 0

Related Questions