Search code examples
phpfilefwrite

How to change a specific line in a text file


I have following situation, I get several checkboxes, each of checkboxes has a value like 1, 2, 3 etc, this reffares to a certain position in array and certain line in a text file.

I need to somehow figure out how to update this certain line in a text file for if related checkbox was selected. each input has a name of visitProperty[]

foreach($_POST['visitProperty'] as $check) {
        $fileName = "pdata.txt";
        $fileContent = file($fileName);
        $readFile = fopen($fileName, "w+");
        $fileContent[$check] = "TEST TO SEE IF LINE REPLACED";
        $update = fwrite($readFile, $fileContent[$check]);
        fclose($readFile);
    }

This is what I tried, but it is not working.


Solution

  • Is this what you are looking for? Where $check is the index in the array?

    $fileName = "pdata.txt";
    $fileContent = file($fileName);
    foreach($_POST['visitProperty'] as $check) {
        $fileContent[$check] = "TEST TO SEE IF LINE REPLACED";
    }
    file_put_contents ($fileName, implode("\n", $fileContent));