What are some potential pitfalls when sorting data from a file in PHP?

One potential pitfall when sorting data from a file in PHP is not properly handling the file read/write operations, which can lead to data corruption or loss. To avoid this, make sure to open and close the file properly before and after reading/writing data.

// Open the file for reading
$file = fopen('data.txt', 'r');

// Read the data from the file
$data = [];
while (!feof($file)) {
    $line = fgets($file);
    // Process the line as needed
    $data[] = $line;
}

// Close the file
fclose($file);

// Sort the data
sort($data);

// Open the file for writing
$file = fopen('data.txt', 'w');

// Write the sorted data back to the file
foreach ($data as $line) {
    fwrite($file, $line);
}

// Close the file
fclose($file);