What are some best practices for reading and sorting data from a file in PHP?

When reading and sorting data from a file in PHP, it is important to follow best practices to ensure efficiency and accuracy. One common approach is to read the file line by line using functions like fopen and fgets, then store the data in an array or object for sorting. To sort the data, you can use built-in PHP functions like usort or ksort depending on the sorting requirements.

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

// Read the file line by line and store data in an array
$data = [];
while (!feof($file)) {
    $line = fgets($file);
    // Process the line and store data in an array
    $data[] = $line;
}

// Close the file
fclose($file);

// Sort the data (e.g. alphabetically)
sort($data);

// Output the sorted data
foreach ($data as $line) {
    echo $line . "<br>";
}