How can I ensure that data is written to the exact line specified in a PHP file when using file handling functions?

When using file handling functions in PHP, it can be challenging to ensure that data is written to the exact line specified in a file. One way to achieve this is by reading the contents of the file into an array, making the necessary changes to the specific line, and then writing the updated array back to the file. This approach allows you to target a specific line for modification without overwriting the rest of the file.

<?php
// Specify the file path
$file = 'example.txt';

// Read the file into an array
$lines = file($file);

// Modify the specific line (e.g., line 3)
$lines[2] = "This is the new content for line 3\n";

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