What is the best practice for reading specific lines from a file in PHP and writing them to another file without using ftruncate?

When reading specific lines from a file in PHP and writing them to another file without using ftruncate, you can achieve this by reading the file line by line, storing the lines you want to keep in an array, and then writing those lines to the new file. This approach allows you to selectively copy specific lines without truncating the file.

<?php

$fileToRead = 'file1.txt';
$fileToWrite = 'file2.txt';
$linesToKeep = [2, 4, 6]; // Specify the line numbers you want to keep

$lines = file($fileToRead);
$selectedLines = [];

foreach ($linesToKeep as $lineNumber) {
    if (isset($lines[$lineNumber - 1])) {
        $selectedLines[] = $lines[$lineNumber - 1];
    }
}

file_put_contents($fileToWrite, implode("", $selectedLines));

?>