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
CodePudding user response:
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 $raisedGrade\n";
} else {
$raisedGrade = $grade;
// echo "NOT raising $grade\n";
}
fwrite($results, $raisedGrade . "\n");
echo $raisedGrade . "\n";
}
fclose($results);
CodePudding user response:
Because in foreach where you output the grades you still youse $read_start what is the old file without your updates. This foreach
foreach($read_start as $key){
fwrite($open_start,raise($key));
}
Should be replaced with inserting new grades to the new file instead of old file. Like this
foreach($read_start as $key){
fwrite($open_end,raise($key));
}
And the last foreach should use new file