How can PHP be used to efficiently extract and sort data from a text file containing user information?

To efficiently extract and sort data from a text file containing user information in PHP, you can read the file line by line, extract the relevant data, store it in an array, and then use PHP's array sorting functions to sort the data based on a specific criteria, such as user ID or name.

<?php
// Open the text file containing user information
$file = fopen('users.txt', 'r');

// Initialize an empty array to store user data
$users = [];

// Read the file line by line
while (($line = fgets($file)) !== false) {
    // Extract user information from each line (assuming the data is comma-separated)
    $userData = explode(',', $line);
    
    // Store the user information in the users array
    $users[] = [
        'id' => $userData[0],
        'name' => $userData[1],
        'email' => $userData[2]
    ];
}

// Close the file
fclose($file);

// Sort the users array based on user ID
usort($users, function($a, $b) {
    return $a['id'] - $b['id'];
});

// Print the sorted user data
foreach ($users as $user) {
    echo $user['id'] . ' - ' . $user['name'] . ' - ' . $user['email'] . PHP_EOL;
}
?>