How can one edit a specific line in a file that has been read into an array in PHP?

To edit a specific line in a file that has been read into an array in PHP, you can access the line by its index in the array, make the necessary changes, and then write the updated array back to the file. You can use the file() function to read the file into an array, modify the specific line using array indexing, and then use the implode() function to convert the array back into a string and write it back to the file.

$file = 'example.txt';
$lines = file($file);

$lineNumber = 2; // Line number to edit
$newLineContent = 'New content for line 2';

$lines[$lineNumber - 1] = $newLineContent . "\n"; // Update the specific line

file_put_contents($file, implode('', $lines)); // Write the updated array back to the file