What is the best practice for deleting a specific line in a .txt file using PHP?

When deleting a specific line in a .txt file using PHP, one approach is to read the file line by line, skip the line that needs to be deleted, and then rewrite the remaining lines to a new file. Once the new file is complete, it can replace the original file to effectively delete the specified line.

$filename = 'example.txt';
$line_number = 3; // Line number to delete

$lines = file($filename, FILE_IGNORE_NEW_LINES);
unset($lines[$line_number - 1]);

$new_content = implode("\n", $lines);
file_put_contents($filename, $new_content);