settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Student Academy - PHP Associative Arrays Task

+2 votes

Write a program, which keeps information about students and their grades.

You will receive n pair of rows. First you will receive the student's name, after that you will receive his grade. Check if student already exists, and if not, add him. Keep track of all grades for each student.

When you finish reading data, keep students with average grade higher or equal to 4.50. Order filtered students by average grade in descending.

Print the students and their average grade in format:

"{name} –> {averageGrade}"

Format the average grade to the 2nd decimal place.

Examples:

student academy php associative arrays task

asked in JavaScript category by user hues

1 Answer

+1 vote

Here is my solution with 3 associative arrays:

<?php

$studentsCount = intval(readline());
$studentGradeTotal = [];//1st associative array
$studentGradeCount = [];//2nd associative array

for ($i = 0; $i < $studentsCount; $i++) {

    $name = readline();
    $grade = floatval(readline());

    if (!key_exists($name, $studentGradeTotal)) {
        $studentGradeTotal[$name] = $grade;
        $studentGradeCount[$name] = 1;
    } else {
        $studentGradeTotal[$name] += $grade;
        $studentGradeCount[$name]++;
    }
}

$studentsAverageGrade = [];//3rd associative array
foreach ($studentGradeTotal as $name => $grade) {
    $average = number_format(($grade / $studentGradeCount[$name]), 2);
    $studentsAverageGrade[$name] = $average;
}

arsort($studentsAverageGrade);
foreach ($studentsAverageGrade as $k => $v) {
    if ($v >= 4.50) {
        echo "$k -> $v" . PHP_EOL;
    }
}
answered by user andrew
...