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: 
```
<?php
$file = file("states.txt");
sort($file);
$newContent = "";
for($i=0; $i<count($file); $i++)
{
  $states = explode(",", $file[$i]);
  $newContent .= $states[0] .', '. $states[1] . PHP_EOL;
}

file_put_contents('states.txt',$newContent);
?>

```

[PHP: file\_put\_contents](http://php.net/manual/en/function.file-put-contents.php)
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.