How can one efficiently insert a new data entry in a sorted text file without reading the entire file in PHP?

To efficiently insert a new data entry in a sorted text file without reading the entire file in PHP, you can use a binary search algorithm to find the correct position for the new entry based on the sorting criteria. Once the position is found, you can open the file in "r+" mode to insert the new data entry at that position without having to read the entire file.

// Define the data entry to be inserted
$newEntry = "New data entry";

// Open the file in read/write mode
$file = fopen("sorted_file.txt", "r+");

// Binary search to find the correct position for insertion
while (!feof($file)) {
    $currentPosition = ftell($file);
    $line = fgets($file);
    if ($line > $newEntry) {
        break;
    }
}

// Insert the new data entry at the correct position
fseek($file, $currentPosition);
fwrite($file, $newEntry . PHP_EOL);

// Close the file
fclose($file);