PHP file handling read and write

Converting string to Date and DateTime
Upload a file using PHP

In this article, we will figure out how file handling works.

problem statement

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.

https://stackoverflow.com/questions/69752768/php-file-handling-read-and-write

solution 1

file() reads a file into an array, so you’d need to take them 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);
Converting string to Date and DateTime
Upload a file using PHP

Stay up-to-date about PHP!

We don’t spam!

en English
X
Scroll to Top