Zera
Zera

Reputation: 15

Working out averages using two dimensional arrays in PHP

I am very new at coding in PHP and I am trying to find out the averages mark of my students so they can view it on an online form. How would I find the averages for the following using a two dimensional array in PHP?

             Maths English Science
Student 1     50     92      62
Student 2     84     71      76
Student 3     67     87      68

I would need the average for:

This is what I have so far:

<?php
$classMarks = array
(
'student 1' => array(50,92,62),
'student 2' => array(84,71,76),
'student 3' => array(67,87,68),
'maths' => array(50,84,67),
'english' => array(92,71,87),
'science' => array(62,76,68),
);

Upvotes: 1

Views: 96

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 78994

No need to duplicate the data, you can just use:

$classMarks = array
(
'student 1' => array(50,92,62),
'student 2' => array(84,71,76),
'student 3' => array(67,87,68),
);

For the students, sum the particular student's scores, in this case student 1 and divide by the count of scores:

$student1 = array_sum($classMarks['student 1']) / count($classMarks['student 1']);

For the subjects, since maths is in the fist position (offset 0) then extract all values in offset 0, english would be offset 1, etc and compute the average the same way:

$maths   = array_sum($subj = array_column($classMarks, 0)) / count($subj);
$english = array_sum($subj = array_column($classMarks, 1)) / count($subj);

But a more meaningful structure might be:

$classMarks = array
(
'student 1' => array('maths'=>50,'english'=>92,'science'=>62),
'student 2' => array('maths'=>84,'english'=>71,'science'=>76),
'student 3' => array('maths'=>67,'english'=>87,'science'=>68),
);

Then access the subjects by their key such as maths:

$maths = array_sum($subj = array_column($classMarks, 'maths')) / count($subj);

Upvotes: 2

clearshot66
clearshot66

Reputation: 2302

A foreach loop

Loop each element as a student key = > averages value Then add them, position 0 1 and 2, then divide by 3 (3 scores). I broke it up so you can see the steps, but it can be done within 1 line.

Then create the new array holding the averages

foreach($classMarks as $student => $averages){

$averaged = $averages[0] + $averages[1] + $averages[3];
$averaged = $average / count($classMarks($student);
$newArray[] = [$student = > averaged];
}

print_r($newArray);

Upvotes: 0

splash58
splash58

Reputation: 26153

If you get array with structure as in the question, you can calculate averages in such way

$avg = array();

foreach($classMarks as $k=>$v) {
  $avg[$k] = array_sum($classMarks[$k]) / count($classMarks[$k]);
}

print_r($avg);

Upvotes: 0

Related Questions