What is the best approach to delete a specific line in a text file using PHP?

To delete a specific line in a text file using PHP, you can read the contents of the file, remove the line you want to delete, and then rewrite the modified content back to the file. One approach is to read the file line by line, skip the line you want to delete, and then write the remaining lines to a new file. Finally, replace the original file with the new file to complete the deletion process.

<?php
$filename = 'example.txt';
$line_number_to_delete = 3;

// Read the contents of the file
$lines = file($filename);

// Open the file for writing
$file = fopen($filename, 'w');

// Loop through each line and write to the file, skipping the line to delete
foreach($lines as $key => $line) {
    if($key + 1 != $line_number_to_delete) {
        fwrite($file, $line);
    }
}

// Close the file
fclose($file);
?>