How can you write the value of a variable back into a specific line of a .txt file in PHP?

To write the value of a variable back into a specific line of a .txt file in PHP, you can read the contents of the file, replace the specific line with the new value, and then write the updated contents back to the file. You can achieve this by using functions like file(), implode(), and file_put_contents().

$file = 'example.txt';
$lineNumber = 2;
$newValue = 'new value';

$lines = file($file);
$lines[$lineNumber - 1] = $newValue . PHP_EOL;
file_put_contents($file, implode('', $lines));