You probably should use a database instead of a text file, as a text file will get slow as it you the guest book gets bigger. However with your text file way:
First, store the email address, as a hash not an array, because when you sort the usernames, the order won't be the same, so the email address won't match.
PHP Code:
$emails[$username] = $data[1];
# instead of $emails[$row] = $data[1];
Now in the segment that rewrites the guest book file, your have to write the hole sorted table, with your new guest in alphabetical order. To avoid potentially overrighting a good record file, while another webuser is reading its, and additional get a file lock so only one process get right to it at a time. Lookup flock in the php manual, you'll also need a shared lock, when you first read the file. Rembember with php code and webserver, multiple people could be reading the same page at a time. A database would handle this for you, but if your using files, you should get 'locks' on them, when you start to read or write them.
For sorting, just use "sort" or "natsort" on the usernames array, and grab the email
address from the associative array of emails.
PHP Code:
if (!$error){
fopen($fh, "records.txt.new","r+") || die("failed writing guest book record");
if (flock($fh,LOCK_EX){ # Exclusive lock on the file
ftruncate("records.txt"); # Start from blank
natsort($usernames); # This will sort in alphanumeric order
foreach($usernames as $user){
fwrite($user.",".$email[$user]."\n");
}
flock($fh, LOCK_UN); # unlock it
fclose($fh);
} else {
fclose($fh);
die(" could get a lock on records.txt");
}
}
}