I am trying to figure out how the file handling works, the thread says:
Your task is to write a PHP script, which reads grades from the file “grades.txt”, raises all of them by one, writes the raised grades into the file “results.txt”, and finally prints the raised grades from the file “results.txt“. If a grade is 5, it won’t be raised. In grades.txt, each grade is on its own line, and the amount of grades may vary. Each grade is 0-5. The grades have to be written on their own lines to results.txt as well.
<?php function raise($n){ if ($n == 5 ){ return 5 ; }else{ return $n + 1 . "n"; } } $start= 'grades.txt'; $read_start=file($start); $open_start=fopen($start,'w'); $end = 'results.txt'; $open_end=fopen($end,'w'); foreach($read_start as $key){ fwrite($open_start,raise($key)); } echo "New grades: ". "n"; foreach($read_start as $value){ fwrite($open_end, $value); echo $value; } ?>
The expected output should be, all the raised grades should be written into the results.txt:
New grades: 1 5 2 4 3 5
But my code gave me this:
1 2 4 3 5 New grades: 0 5 1 3 2 4
Advertisement
Answer
file() reads a file into an array, so you’d need to take the key
into account (in foreach ($grades as $key => $grade) {
). You should also make sure that the values you get are actually integer ($grade = (int) $grade;
). Then loop over the grades and write/output the new grade accordingly:
<?php $grades = file("grades.txt"); $results = fopen("results.txt", "w"); // print_r($grades); foreach ($grades as $key => $grade) { $grade = (int) $grade; if($grade != 5) { $raisedGrade = $grade + 1; // echo "raising $grade to $raisedGraden"; } else { $raisedGrade = $grade; // echo "NOT raising $graden"; } fwrite($results, $raisedGrade . "n"); echo $raisedGrade . "n"; } fclose($results);