So I have a task where I should read a text file in php, containing students IDs and their grades, separated by vertical lines. It looks something like that:
12345|4|2|1|0|4
45678|1|2|3|4|4
78901|5|5|5|5|4
The program should print the amount of students there are on the file, which I managed to do by simply echoing the amount of lines. However, I should also print the sum of the grades for each student, and I simply can't find a way to do it. Do I get the characters by order on the line or something similar? I've been struggling with this for a day now and I only got as far as this:
<?php
$file="exam.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
echo "total_students was $linecount:";
$homepage = file_get_contents('exam.txt');
echo $homepage;
?>
This code only prints the page and the amount of lines, nothing more.
So after I was guided in the right direction I managed to come up with a solution!
<?php
$file="exam.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
echo "total_students was $linecount:
";
$lines = file('exam.txt');
$sum = 0 ;
foreach ($lines as $line){
$var = explode("|", $line);
$sum = $var[1]+$var[2]+$var[3]+$var[4]+$var[5];
$all += $sum;
echo "$var[0]: $sum points
";
}
$average = $all / $linecount;
echo "The average score was $average points."
?>
I exploded each line as an array divided by the "|" symbol, then I printed the student ID from the [0] of the array, and summed the rest. After that I summed the sums and thus found the average.