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

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.


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:


$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;

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

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