faqts : Computers : Programming : Languages : PHP : Common Problems : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

9 of 16 people (56%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

How can I sort a file so that rows would be in alphabetical order?

Feb 3rd, 2002 03:09
Philip Olson, Ben Udall, Tomi Peltola,


Let's use file() to open our file as an array, then use sort() to sort
that array.  First:
  file -- Reads entire file into an array
          http://www.php.net/file
<?php
  $filename = 'somefile.txt';
  if (!is_readable($filename)) {
    print "Error: File ($filename) is not readable";
    exit;
  }
  $lines = file($filename);
  // also consider natsort
  $lines = sort($lines);
  foreach ($lines as $line) {
    print $line;
  }
?>
Of course you'll output it differently but point is, opening with file()
and sorting the array is a good way to accomplish this task.