Question: I have a question. I am in process of learning how to read/write files, but having little trouble trying to do both at the same time in same php script. I have a text file with words like this,

```
Richmond,Virginia
Seattle,Washington
Los Angeles,California
Dallas,Texas
Jacksonville,Florida

```

I wrote a code to sort them in order and this will display in sort order by City.

```
<?php
$file = file("states.txt");
sort($file);
for($i=0; $i<count($file); $i++)
{
  $states = explode(",", $file[$i]);
  echo $states[0], $states[1],"<br />";
}
?>

```

From this, how can I rewrite those sorted information back into the states.txt file?

Answer: 
this is a little extended, however I thought it might be useful to smb. I have an m3u playlist and need only particular rows filtered, sorted and printed. Credits go to Devil:

```
<?php

//specify that the variable is of type array
$masiv = array();

//read the file
$file = '/home/zlobi/radio/pls/all.m3u';  

$f = fopen($file, "r");

while ($line = fgets($f))
{
//skip rows with #EXT
if(strpos($line, "#EXT") !== false) continue;

$text = str_replace('.ogg', ' ', $line);  
$text = str_replace('/home/zlobi/radio/',' ',$text);

//add the song as an element in an array
$masiv[] = $text;
}
$f = fclose($f);

//sort the array
sort($masiv);

//pass via the array, take each element and print it
foreach($masiv as $pesen)

print $pesen.'<br/>';

?>

```

masiv is array, pesen is song in Bulgarian :)
CAPital letters are sorted first.

Regads
This is by far the fastest and most elegant solution that I have found, when I had the same problem.
If you're on Linux (with exec allowed in PHP configuration) you can do the following (provided you want to sort files numerically):

```
exec("sort -n " . $pathToOriginalFile . " > " . $pathToSortedFile);

```

Basically, execute bash command **sort** that sorts the lines in a file numerically.
If you want to keep the data in the original file do this:

```
exec("sort -n " . $pathToOriginalFile . " > " . $pathToSortedFile);
exec("rm " . $pathToOriginalFile);
exec("mv " . $pathToSortedFile . " " . $pathToOriginalFile);

```

If you want an alphabetical sort just exclude -n (--numeric-sort) option.

```
exec("sort " . $pathToOriginalFile . " > " . $pathToSortedFile);

```

For me the command took about 3 seconds to sort 10 million lines in the file on the server.

You can find more about sort here <http://www.computerhope.com/unix/usort.htm>

Hope it helps.