What are the best practices for inserting or deleting a line in a file using PHP?
When inserting or deleting a line in a file using PHP, it is important to read the entire file into memory, make the necessary changes, and then write the modified content back to the file. To insert a line, you can use functions like `file()` to read the file into an array, `array_splice()` to insert the new line at the desired position, and `file_put_contents()` to write the updated content back to the file. To delete a line, you can use similar functions to remove the line from the array before writing it back to the file.
// Insert a line in a file
$filename = 'example.txt';
$lines = file($filename); // Read file into an array
$lineNumber = 2; // Line number to insert the new line after
$newLine = "This is the new line\n";
array_splice($lines, $lineNumber, 0, $newLine); // Insert new line
file_put_contents($filename, implode('', $lines)); // Write back to file
// Delete a line from a file
$filename = 'example.txt';
$lines = file($filename); // Read file into an array
$lineToDelete = 2; // Line number to delete
unset($lines[$lineToDelete]); // Remove line
file_put_contents($filename, implode('', $lines)); // Write back to file